C plus plus programming
June 3, 2026 2 min read

Set and methods in c plus plus programming

HS
HEMANT SINGH
Technical Writer & Educator

std::set Operations

The std::set in C++ is a part of the Standard Template Library (STL) and is used to store unique elements in a sorted manner. It automatically removes duplicates and arranges elements in ascending order (by default).

🛠️ Commonly Used Operations in std::set

1. insert(value)

Adds a new value to the set. If the value already exists, it will not be added again.

std::set s;
s.insert(10);
s.insert(20);

2. erase(value)

Removes a specific value from the set.

s.erase(10);

3. find(value)

Returns an iterator pointing to the value if found, otherwise returns s.end().

if (s.find(20) != s.end()) {
    std::cout << "Found!" << std::endl;
}

4. count(value)

Returns 1 if the value is present in the set, otherwise returns 0.

if (s.count(20)) {
    std::cout << "Exists!" << std::endl;
}

5. clear()

Removes all elements from the set, making it empty.

s.clear();

6. size()

Returns the number of elements currently stored in the set.

std::cout << "Size: " << s.size();

7. empty()

Returns true if the set is empty; otherwise, returns false.

if (s.empty()) {
    std::cout << "Set is empty"; 
}

8. begin() and end()

begin() returns an iterator to the first element.

end() returns an iterator to the position after the last element.

for (auto it = s.begin(); it != s.end(); ++it) {
    std::cout << *it << " ";
}

In this category