Home C++ C++ Standard Template Library (STL) set tutorial

C++ Standard Template Library (STL) set tutorial

The set in the C++ Standard Template Library (STL) is an associative container that stores unique elements in a sorted order.

It is particularly useful when you need to store a collection of distinct items without duplicates and in a specific order.

Key Features of set

  1. Unique Elements: Each element in a set is unique, and duplicate elements are automatically ignored.
  2. Sorted Order: Elements are stored in ascending order by default.
  3. Efficient Operations: Provides efficient insertion, deletion, and search operations.

Basic Syntax

#include <set>
using namespace std;

set<Type> s;

Let’s explore the set with examples of common operations.

1. Initializing and Inserting Elements

You can initialize a set with values and insert elements using the insert function. Duplicate elements will not be added to the set.

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

int main() {
    set<int> s;

    // Insert elements
    s.insert(10);
    s.insert(20);
    s.insert(10); // Duplicate, will be ignored
    s.insert(15);

    // Display elements
    cout << "Elements in the set: ";
    for (const auto &val : s) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

Output:

Elements in the set: 10 15 20 

2. Checking if an Element Exists

The find function returns an iterator to the element if it exists, otherwise it returns set::end. The count function can also be used to check if an element exists.

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

int main() {
    set<int> s = {10, 20, 30};

    // Using find()
    if (s.find(20) != s.end()) {
        cout << "Element 20 is in the set." << endl;
    } else {
        cout << "Element 20 is not in the set." << endl;
    }

    // Using count()
    if (s.count(40) > 0) {
        cout << "Element 40 is in the set." << endl;
    } else {
        cout << "Element 40 is not in the set." << endl;
    }

    return 0;
}

Output:

Element 20 is in the set.
Element 40 is not in the set.

3. Removing Elements

You can remove elements from a set using the erase function, either by specifying the value or an iterator position.

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

int main() {
    set<int> s = {10, 20, 30, 40};

    // Remove element by value
    s.erase(20);

    // Remove element by iterator
    auto it = s.find(30);
    if (it != s.end()) {
        s.erase(it);
    }

    // Display remaining elements
    cout << "Elements after removal: ";
    for (const auto &val : s) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

Output:

Elements after removal: 10 40 

4. Checking if the Set is Empty

The empty function checks if the set has any elements, returning true if it’s empty and false otherwise.

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

int main() {
    set<int> s;

    // Check if the set is empty
    if (s.empty()) {
        cout << "The set is empty." << endl;
    }

    // Add an element and check again
    s.insert(5);
    if (!s.empty()) {
        cout << "The set is not empty." << endl;
    }

    return 0;
}

Output:

The set is empty.
The set is not empty.

5. Getting the Size of the Set

The size function returns the number of elements in the set.

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

int main() {
    set<int> s = {10, 20, 30};

    // Display the size of the set
    cout << "Size of the set: " << s.size() << endl;

    return 0;
}

Output:

Size of the set: 3

6. Using set with Custom Data Types

You can store custom objects in a set by defining a custom comparator for sorting.

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

// Custom structure for people with a comparator
struct Person {
    string name;
    int age;

    bool operator<(const Person &other) const {
        return age < other.age;  // Sort by age
    }
};

int main() {
    set<Person> s;

    // Insert custom objects
    s.insert({"Alice", 25});
    s.insert({"Bob", 30});
    s.insert({"Charlie", 20});

    // Display elements
    cout << "People in the set:" << endl;
    for (const auto &person : s) {
        cout << person.name << " (" << person.age << ")" << endl;
    }

    return 0;
}

Output:

People in the set:
Charlie (20)
Alice (25)
Bob (30)

7. Using lower_bound and upper_bound

The lower_bound and upper_bound functions return iterators to specific positions in the set. lower_bound returns the first element not less than a given value, and upper_bound returns the first element greater than a given value.

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

int main() {
    set<int> s = {10, 20, 30, 40, 50};

    // Lower bound of 25
    auto lb = s.lower_bound(25);
    if (lb != s.end()) {
        cout << "Lower bound of 25: " << *lb << endl;
    }

    // Upper bound of 30
    auto ub = s.upper_bound(30);
    if (ub != s.end()) {
        cout << "Upper bound of 30: " << *ub << endl;
    }

    return 0;
}

Output:

Lower bound of 25: 30
Upper bound of 30: 40

8. Using set with Custom Comparator

You can define a custom comparator to change the sorting order of elements in the set.

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

// Custom comparator for descending order
struct DescendingOrder {
    bool operator()(int a, int b) const {
        return a > b;
    }
};

int main() {
    set<int, DescendingOrder> s;

    // Insert elements
    s.insert(10);
    s.insert(5);
    s.insert(20);

    // Display elements in descending order
    cout << "Elements in descending order: ";
    for (const auto &val : s) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

Output:

Elements in descending order: 20 10 5 

9. Clearing the Set

The clear function removes all elements from the set, making it empty.

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

int main() {
    set<int> s = {10, 20, 30};

    cout << "Size before clear: " << s.size() << endl;

    // Clear the set
    s.clear();

    cout << "Size after clear: " << s.size() << endl;

    return 0;
}

Output:

Size before clear: 3
Size after clear: 0

10. Initializing a Set with a Range

You can initialize a set with elements from an array or vector by passing a range of values.

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

int main() {
    vector<int> vec = {10, 20, 10, 30, 20};

    // Initialize set with vector elements
    set<int> s(vec.begin(), vec.end());

    cout << "Elements in the set: ";
    for (const auto &val : s) {
        cout << val << " ";
    }
    cout << endl;

    return 0;
}

Output:

Elements in the set: 10 20 30 

Summary Table of set Operations

Operation Code Example Description
Initialize set<int> s = {10, 20}; Creates a set with initial values
Insert Element s.insert(10); Inserts an element (ignores duplicates)
Check if Element Exists s.find(10) != s.end(); Checks if an element exists
Remove Element s.erase(10); Removes an element
Check if Empty s.empty(); Checks if the set is empty
Get Size s.size(); Returns the number of elements
Custom Comparator set<int, Comparator> s; Creates a set with custom sorting
Clear s.clear(); Removes all elements
Range Initialization set<int> s(vec.begin(), vec.end()); Initializes set with a range of elements
Lower Bound s.lower_bound(15); Returns iterator to first element not less than
Upper Bound s.upper_bound(15); Returns iterator to first element greater than

Complete Example

This example demonstrates initializing a set, adding and removing elements, checking if elements exist, and clearing the set.

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

int main() {
    set<int> s;

    // Insert elements
    s.insert(5);
    s.insert(10);
    s.insert(15);

    // Check if elements exist
    cout << "Does 10 exist? " << (s.count(10) > 0 ? "Yes" : "No") << endl;

    // Display all elements
    cout << "Elements in the set: ";
    for (const auto &val : s) {
        cout << val << " ";
    }
    cout << endl;

    // Remove an element
    s.erase(10);
    cout << "Elements after removing 10: ";
    for (const auto &val : s) {
        cout << val << " ";
    }
    cout << endl;

    // Clear the set
    s.clear();
    cout << "Is the set empty? " << (s.empty() ? "Yes" : "No") << endl;

    return 0;
}

Sample Output:

Does 10 exist? Yes
Elements in the set: 5 10 15 
Elements after removing 10: 5 15 
Is the set empty? Yes

Key Takeaways

  • set in C++ stores unique elements in sorted order, making it ideal for collections that require no duplicates.
  • It provides efficient methods for insertion, deletion, and lookup operations.
  • Custom comparators enable control over sorting order, and lower_bound / upper_bound help with range-based queries.

You may also like