Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Set Stl

User image

Published by

sanya sanya

Published at: 4th Aug, 2023
1.92 mins read

The C++ Standard Template Library (STL) provides a set container that is a part of the associative container class templates. The set is an ordered collection of unique elements in which the elements are stored in a specific order based on a comparison function, and no two elements can have the same value.

Key Characteristics of set:

- Elements are stored in a specific sorted order.

- The keys are unique and cannot have same value.

- Elements are inserted in a way that maintains the sorted order.

- Searching, insertion, and deletion operations take O(log n) time on average.

- Implemented as a balanced binary search tree.

Including the STL set header:

To use the ‘set’, include the ‘‘ header file.

#include

Declaration and Initialization:

Set can be declared and initialized in various ways:

set mySet; // Empty set of integers

set strSet {"apple", "banana", "orange"}; // Set of strings with initial values

Insertion:

Elements can be inserted using the ‘insert()’ member function:

mySet.insert(10); // Insert 10 into the set

mySet.insert(20); // Insert 20 into the set

Access and Searching:

Sets do not provide direct access to elements using an index since they are ordered collections. ‘Find()’ can be used to search for elements:

auto it = mySet.find(20);

if (it != mySet.end()) {

cout << "Element found: " << *it << endl;

} else {

cout << "Element not found!" << endl;

}

Deletion:

Elements can be removed from the set using ‘erase()’:

mySet.erase(20); // Remove element 20 from the set

Iterating through a Set:

Use iterators to traverse the elements of the set:

for (auto it = mySet.begin(); it != mySet.end(); ++it) {

cout << *it << " ";

}

Set Operations:

set set1 {1, 2, 3, 4, 5};

set set2 {3, 4, 5, 6, 7};

// Union

set unionSet;

set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(unionSet, unionSet.begin()));

// Intersection

set intersectionSet;

set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(intersectionSet, intersectionSet.begin()));

// Difference

set differenceSet;

set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(differenceSet, differenceSet.begin()));

Custom Comparator:

By default, sets are sorted in ascending order. A custom comparison function can be defined to change the sorting order:

‘‘‘cpp

bool customComparator(int a, int b) {

// Define your custom comparison logic

return a > b; // Sort in descending order

}

set<int, decltype(customComparator)*> mySet(customComparator);

mySet.insert(10);

mySet.insert(20);

Library

WEB DEVELOPMENT

FAANG QUESTIONS