Sets in C++
Set (set)
— it is a container that automatically sorts the added elements in ascending order. But when adding identical values, set
will only store one instance of it (multiset
- multiset- may contain duplicates). When a new element is added to the set, it immediately falls into place so as not to violate the sort order.
Sets in C++ are defined in the STL
standard template library through the class set (multiset)
.
Sets are binary red-black trees. Search, delete, and insert operations have logarithmic complexity.
To use sets, you need to include the “
set
” library:
#include <set>
Set declaration:
set<int> mySet; // Declaring an empty set.
multiset<int> mySet; // Declaring an empty multiset.
Functions for working with a set (set)
empty()
- checks for the absence of elements in the container
size()
- Returns the number of elements in the container
clear()
- Clears the container
insert()
- Inserts elements
erase()
- Removes elements
count()
- Returns the number of elements matching a given key
find()
- Finds an element with a specific key
lower_bound()
- Returns an iterator to the first element no less than the given value
upper_bound()
- Returns an iterator to the first element greater than the specified value
Set and multiset example
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> mySet1; // declared an empty set
multiset<int> mySet2; // declared an empty multiset
// add elements to the set
mySet1.insert(1);
mySet1.insert(2);
mySet1.insert(3);
mySet1.insert(1);
// add elements to the multiset
mySet2.insert(1);
mySet2.insert(2);
mySet2.insert(3);
mySet2.insert(1);
set<int>::iterator it; //create an iterator
for(it = mySet1.begin(); it != mySet1.end(); it++) { // Display all elements
cout << (*it) << " "; // sets
}
cout << endl;
for(it = mySet2.begin(); it != mySet2.end(); it++) { // Output all elements
cout << (*it) << " "; // multisets
}
return 0;
}