2018-10-19 10:59:50 +01:00
---
title: C++ STL Sets
---
## Introduction of sets in C++ STL library
2019-02-18 03:42:48 +05:30
Sets are a type of associative container in which each element has to be unique. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element. They are implemented using [red-black tree ](https://guide.freecodecamp.org/algorithms/red-black-trees/ ).
2018-10-12 15:37:13 -04:00
2018-10-19 10:59:50 +01:00
## Benefits of using sets
2018-10-12 15:37:13 -04:00
1. It stores only unique values.
2. Value of the element identifies itself. The value of an element is also the key used to identify it.
3. Provides a fast lookup (O(log n)) using keys i.e. element itself.
4. There are many inbuilt functions in class defining sets that ease the programming.
Example:
2019-05-11 04:34:50 +05:30
```cpp
2019-02-18 03:42:48 +05:30
#include<iostream>
#include <set>
using std::set;
using std::cout;
using std::endl;
2019-05-11 04:34:50 +05:30
2018-10-12 15:37:13 -04:00
int main()
{
set < int > s;
s.insert(2); //insert element 2 in set s
s.insert(3);
s.insert(5);
s.insert(2); //inserting same element 2
s.insert(6);
for(auto i:s)
2019-02-18 03:42:48 +05:30
cout < < i < < " " ;
cout < < s.size ( ) < < endl ; / / gives the size of set
2018-10-19 10:59:50 +01:00
2018-10-12 15:37:13 -04:00
s.erase(5); // erasing element 5 from set s
return 0;
}
2018-10-19 10:59:50 +01:00
```
2019-02-18 03:42:48 +05:30
[Try this code out yourself! ](https://wandbox.org/permlink/XIFK4d9suQdGniFm )
2018-10-19 10:59:50 +01:00
2018-10-12 15:37:13 -04:00
Creating a set object
2019-05-11 04:34:50 +05:30
```cpp
2018-10-12 15:37:13 -04:00
set < int > s;
2018-10-19 10:59:50 +01:00
```
2018-10-12 15:37:13 -04:00
Insertion
2019-05-11 04:34:50 +05:30
```cpp
2018-10-12 15:37:13 -04:00
s.insert(value_to_be_inserted);
2018-10-19 10:59:50 +01:00
```
2018-10-12 15:37:13 -04:00
Accessing set elements
2019-05-11 04:34:50 +05:30
```cpp
2018-10-12 15:37:13 -04:00
set < int > ::iterator it;
2019-02-18 03:42:48 +05:30
for(it = s.begin(); it != s.end(); ++it)
cout < < *it;
2018-10-19 10:59:50 +01:00
```
2019-05-11 04:34:50 +05:30
## Reference Links
2018-10-12 15:37:13 -04:00
2019-05-11 04:34:50 +05:30
[Geeks for Geeks link to C++ stl ](https://www.geeksforgeeks.org/set-in-cpp-stl/ )
2018-10-12 15:37:13 -04:00