C++ Sets

C++ Sets: Unique and Sorted

In C++, a Set is a container that holds a collection of unique elements.

Sets have two very special rules:

  1. No Duplicates: If you try to add an item that already exists in the set, the set ignores it.
  2. Automatically Sorted: A standard C++ set will automatically sort its elements in ascending order as you add them!

1. Creating and Using a Set

Include the <set> library to use this data structure.

Because elements in a set are constantly shifting to stay sorted, you cannot access them via an index (like mySet[0]).

Set Example

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

int main() { // Create a set of integers set<int> mySet;

// Insert elements mySet.insert(50); mySet.insert(10); mySet.insert(30);

// Try to insert a duplicate! mySet.insert(10);

// Iterate through the set (Notice it's sorted automatically!) for (int num : mySet) { cout << num << " "; // Output: 10 30 50 }

cout << "\nTotal unique elements: " << mySet.size() << "\n";

return 0; }


2. Fast Searching with Sets

Under the hood, C++ sets are typically implemented as Binary Search Trees. This makes finding data incredibly fast. You can check if an item exists in the set using the .count() method (which returns 1 if it exists, and 0 if it doesn't).


Exercise

?

What happens if you insert the numbers 5, 2, and 5 into a C++ set?