Core Module
12 min forge
C++ STL Set
Mastering unique element collections with automatic sorting.
C++ STL Set
π What is it
std::set is an associative container that contains a sorted set of unique objects of type Key. Like std::map, it's usually implemented as a balanced binary search tree.
β‘ When to use
Use std::set when you need to store a collection of unique elements and keep them sorted at all times.
π§ Time complexity
- Insertion: $O(\log N)$
- Search: $O(\log N)$
- Removal: $O(\log N)$
π» Code example
cpp Standard#include <set> #include <iostream> std::set<int> st; st.insert(10); st.insert(20); st.insert(10); // Not inserted (strictly unique) std::cout << st.size(); // 2 for (int x : st) std::cout << x << " "; // Prints 10 20
β Common mistakes
- Trying to change an element value while it's in the setβelements are
const. You must remove and re-insert. - Thinking
std::setuses a hash table (that'sstd::unordered_set). - Overusing it when order doesn't matter (unordered versions are faster).