Set in C++ STL (original) (raw)

Last Updated : 9 Apr, 2026

A Set is a container which stores unique elements in some sorted order. It is an implementation of a Self-Balancing Binary Search Tree, specifically a Red-Black Tree which ensures,

Let us take a look at an example to create a set and traverse it.

C++ `

#include #include using namespace std;

int main() {

// Creating an empty set
set<int> s1;

// Initialize set with list 
set<int> s2 = {1, 2, 3, 2, 1}; 

// Traversing the set
for (auto& x : s2)
    cout << x << " ";
cout << endl;

return 0;

}

`

Syntax

The set container is defined as **std::set class template inside ****** header file.

set s;

where,

Basic Operations

Basic operations on set containers are shown below:

1. Inserting Elements

#include #include using namespace std;

int main() { // Initialize set with values set s = {2, 3};

// Inserting an element
s.insert(1);

// Traversing the set
for (auto x : s)
    cout << x << endl;

return 0;

}

`

2. Searching Elements

#include #include using namespace std;

int main() { set s = {1, 2, 3};

// Accessing elements using find()
auto it = s.find(1);
if (it != s.end())
    cout << "Element found: " << *it << endl;

// Accessing elements using count()
if (s.count(2))
    cout << "2 exists in the set" << endl;

// Accessing all elements by traversal
cout << "All elements: ";
for (auto x : s)
    cout << x << " ";
cout << endl;

return 0;

}

`

Output

Element found: 1 2 exists in the set All elements: 1 2 3

3. Traversing

#include #include using namespace std;

int main() { set s = {1, 2, 3};

// Traversing using iterators
for (auto it = s.begin(); it != s.end(); ++it)
    cout << *it << endl;  

return 0;

}

`

4. Deleting Elements

To delete an element from a set, use erase(), it removes the element if it exists, else does nothing.

C++ `

#include #include using namespace std;

int main() { set s = {1, 2, 3, 4};

// Deleting by value
s.erase(2);

// Deleting by iterator
s.erase(s.begin());

// Traversing the set
for (auto i : s)
    cout << i << " ";
cout << endl;

return 0;

}

`