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::set uses a hash table (that's std::unordered_set).
  • Overusing it when order doesn't matter (unordered versions are faster).