C++ Sets


In C++, a Set is a part of the Standard Template Library (STL) that stores unique elements in a specific order. Sets automatically sort their elements and remove duplicates, making them ideal for tasks where uniqueness is important, such as maintaining a list of distinct values or removing duplicates from a dataset.

Sets use a balanced binary search tree (usually a Red-Black Tree) internally, which ensures that operations like insertion, deletion, and search all happen in logarithmic time complexity O(log n).

Key Features of Sets in C++

  • All elements in a set are unique; duplicates are automatically removed.

  • Elements are stored in sorted order by default.

  • Once an element is inserted, its value cannot be modified, though it can be removed and reinserted.

  • Sets provide efficient search, insertion, and deletion operations.

  • Sets are part of the <set> header file in C++ STL.

Syntax of C++ Set

To use a set, include the header <set> and declare it using the following syntax:

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<int> numbers;
    numbers.insert(10);
    numbers.insert(20);
    numbers.insert(10); // duplicate, ignored

    for (int num : numbers) {
        cout << num << " ";
    }
    return 0;
}

Output:

10 20

In this example, the duplicate value 10 is automatically ignored. The set keeps elements in ascending order.

Types of Sets in C++

C++ provides two main types of sets:

  1. set – stores elements in ascending order by default.

  2. multiset – allows duplicate elements and also keeps them sorted.

Example of a multiset:

#include <iostream>
#include <set>
using namespace std;

int main() {
    multiset<int> nums = {10, 20, 10, 30};
    for (int n : nums) {
        cout << n << " ";
    }
    return 0;
}

Output:

10 10 20 30

Important Member Functions of Set

Here are some commonly used functions in C++ sets:

Function Description
insert(value) Adds an element to the set
erase(value) Removes an element from the set
find(value) Returns iterator to the value if found
count(value) Returns 1 if element exists, otherwise 0
clear() Removes all elements from the set
size() Returns the number of elements
empty() Checks if the set is empty
begin() / end() Returns iterator to start and end of the set

Example: Basic Set Operations

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<int> nums = {5, 2, 8, 1};

    cout << "Set elements: ";
    for (int x : nums)
        cout << x << " ";

    nums.insert(3);
    nums.erase(8);

    cout << "\nAfter modifications: ";
    for (int x : nums)
        cout << x << " ";

    return 0;
}

Output:

Set elements: 1 2 5 8
After modifications: 1 2 3 5

Example: Searching in a Set

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<string> names = {"Anita", "Pooja", "Kavya"};

    string searchName = "Pooja";
    if (names.find(searchName) != names.end())
        cout << searchName << " found in set.";
    else
        cout << searchName << " not found.";

    return 0;
}

Output:

Pooja found in set.

Example: Using count() in Set

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<int> nums = {1, 2, 3, 4};
    cout << "Is 3 present? " << nums.count(3) << endl;
    cout << "Is 9 present? " << nums.count(9) << endl;
    return 0;
}

Output:

Is 3 present? 1
Is 9 present? 0

Iterating Over a Set

You can iterate over a set using iterators as well:

for (set<int>::iterator it = nums.begin(); it != nums.end(); ++it) {
    cout << *it << " ";
}

This method gives you more control if you want to erase elements during iteration or access them conditionally.

Erasing Elements from a Set

You can remove elements from a set in three ways:

  1. By value – set.erase(value)

  2. By position – set.erase(iterator)

  3. By range – set.erase(start_iterator, end_iterator)

Example:

nums.erase(2); // Removes element 2
nums.erase(nums.begin()); // Removes first element
nums.erase(nums.begin(), nums.find(5)); // Removes range

Example: Set of Strings

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<string> fruits = {"Apple", "Banana", "Mango", "Apple"};

    for (auto f : fruits)
        cout << f << " ";
    return 0;
}

Output:

Apple Banana Mango

Summary of the Tutorial

C++ sets are an excellent choice for storing unique, sorted data efficiently. They automatically handle duplicate removal and keep elements organized in ascending order. Sets come with a variety of built-in operations like insertion, deletion, and searching, all performed in O(log n) time. When duplicates are allowed, you can use a multiset instead.

Sets are commonly used in real-world applications like filtering unique records, maintaining sorted datasets, and performing quick searches in large data collections.


Practice Questions

  1. Write a C++ program to create a set of integers and perform insert, erase, and display operations.

  2. Create a program that takes a list of numbers from the user and removes duplicates using a set.

  3. Write a C++ program to find whether a given element exists in a set using the find() function.

  4. Build a program that counts how many unique characters are present in a string using a set.

  5. Write a C++ program to merge two sets and display all unique elements in ascending order.

  6. Create a program that finds the intersection of two sets.

  7. Write a C++ program to store names in a set and display them in alphabetical order.

  8. Build a program that removes all elements greater than a given number from a set.

  9. Write a program to compare two sets and check whether they contain the same elements.

  10. Create a C++ program to demonstrate the difference between a set and a multiset using integer values.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top