C++ Set and Map Functions Cheat Sheet
🔍 std::set
✅ Basics
• set<int> s; — Creates an empty set of integers.
• s.insert(x); — Inserts element x .
• s.erase(x); — Erases element x if present.
• s.find(x); — Returns iterator to x or s.end() if not found.
• s.count(x); — Returns 1 if x is present, else 0 .
• s.size() — Returns number of elements.
• s.empty() — Checks if set is empty.
• s.clear() — Removes all elements.
🔄 Iteration
for (auto x : s) {
cout << x << " ";
}
⬆️ Lower & Upper Bound
• s.lower_bound(x) — First element ≥ x .
• s.upper_bound(x) — First element > x .
🔄 Custom Sort Order
set<int, greater<int>> s; // Descending order
🔎 std::map
✅ Basics
• map<string, int> m; — Map from string to int.
• m[key] = value; — Inserts or updates key-value pair.
• m.at(key) — Returns value, throws if key not found.
• m.find(key) — Returns iterator to key or m.end() .
• m.count(key) — 1 if present, 0 otherwise.
• m.erase(key) — Removes key-value pair.
• m.clear() — Clears the map.
1
• m.size() — Number of pairs.
• m.empty() — Checks if map is empty.
🔄 Iteration
for (auto [key, value] : m) {
cout << key << ": " << value << "\n";
}
🔄 Custom Sort Order
map<int, string, greater<int>> m; // Descending by key
📊 Tips & Tricks
⚡ Use unordered for faster access (avg O(1))
• unordered_set<T>
• unordered_map<K, V>
⭐ Compare Two Sets/Maps
if (s1 == s2) // true if identical
if (m1 == m2)
🧹 Erase by Iterator
auto it = s.find(x);
if (it != s.end()) s.erase(it);
Include headers:
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
Let me know if you want Stack/Queue/String cheatsheet next!