C++ sets

A set in C++ is a collection of unique elements stored in a specific order. It automatically keeps the elements sorted and does not allow duplicates.

characteristics of sets

1. Unique Elements: Sets do not allow duplicate elements. If you try to insert a duplicate element, the set will ignore it.

2. Sorted: By default, elements are stored in ascending order. However, you can specify a custom sorting criterion by using a comparator.

3. Efficient Searching: Sets are typically implemented as balanced binary search trees (usually Red-Black trees), which makes searching, inserting, and deleting elements efficient. Operations like insertion, deletion, and search are logarithmic in time complexity (O(log n)).

Example:


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

int main() {
    set mySet;
    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);  
    mySet.insert(10); // Duplicate, will not be added

    // Iterating through the set and printing the elements
    for (int val : mySet) {
        cout << val << " ";
    }
    return 0;
}

Explanation:

  • The set automatically removes the duplicate 10.
  • It stores the elements in sorted order: 10, 20 and 30.

Output:

10 20 30

Complete Example:


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

int main() {
    set mySet;
    
    // Adding elements
    mySet.insert(10);
    mySet.insert(20);
    mySet.insert(30);
    mySet.insert(10);  // This will not be added, as 10 is already in the set
    
    // Displaying elements (automatically sorted in ascending order)
    cout << "Elements in the set: ";
    for (int num : mySet) {
        cout << num << " ";
    }
    cout << endl;
    
    // Checking size
    cout << "get the size: " << mySet.size() << endl;
    
    // Searching for an element
    if (mySet.find(5) != mySet.end()) {
        cout << "5 found in the set." << endl;
    }

    // Erasing an element
    mySet.erase(3);
    cout << "After erasing 3, set size: " << mySet.size() << endl;
    
    return 0;
}

Example:

Elements in the set: 10 20 30
get the size: 3
After erasing 3, set size: 3