Sets
Sets are associative containers which store unique elements that can be referenced by an element’s value. The value, which is itself the key to access an element in the set, is constant. Once assigned it cannot be changed. However, existing values can be removed or new values can be added.
Syntax
std::set<dataType> setName;
A set can be created by using the set
keyword and declaring a data type and name.
Example
The example below initiates a set, inserts values into it using the .insert() method, and then prints out the set:
#include <iostream>#include <set>int main() {// Initiate setstd::set<int> numSet;// Insert values into setnumSet.insert(25);numSet.insert(42);numSet.insert(10);numSet.insert(19);// Print out setstd::set<int> :: iterator iter;for (iter = numSet.begin(); iter != numSet.end(); iter++) {std::cout<< *iter << " ";}}
This outputs the following:
10 19 25 42
By default, values of the set are sorted in ascending order.
Setting a Different Comparison Function
The comparison function can be changed from the default to std::greater<dataType>
in order to sort the values in descending order.
Syntax
std::set<dataType, std::greater<dataType> > setName;
The dataType
for the comparison function must match the data type of the set
.
Codebyte Example
Setting the previous example’s comparison function to std::greater<int>
:
Sets
- .clear()
- Removes all values from a set.
- .erase()
- Removes a single value from a set.
- .insert()
- Inserts a single value into a set.
All contributors
- Christine_Yang271 total contributions
- garanews222 total contributions
- BrandonDusch580 total contributions
- KyraThompson73 total contributions
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.