In C++, a Set is a container that holds a collection of unique elements.
Sets have two very special rules:
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]).
#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; }
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).
What happens if you insert the numbers 5, 2, and 5 into a C++ set?