0% found this document useful (0 votes)
2 views2 pages

Cpp Set Map Cheatsheet

This cheat sheet provides essential functions for C++ sets and maps, including creation, insertion, deletion, and iteration methods. It also covers custom sorting, tips for performance with unordered collections, and how to compare sets and maps. Additionally, it includes necessary header files for usage.

Uploaded by

dev0607sh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Cpp Set Map Cheatsheet

This cheat sheet provides essential functions for C++ sets and maps, including creation, insertion, deletion, and iteration methods. It also covers custom sorting, tips for performance with unordered collections, and how to compare sets and maps. Additionally, it includes necessary header files for usage.

Uploaded by

dev0607sh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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!

You might also like