C++ Map Usage Guide
1. Declaring and Initializing a Map
map<int, int> m;
map<int, int> m = {{1, 10}, {2, 20}, {3, 15}};
2. Iterating Through a Map
for (auto it : m)
cout << it.first << " " << it.second << endl;
for (auto &[key, value] : m)
cout << key << " => " << value << endl;
3. Adding Two Maps
for (auto &[key, value] : m2)
m1[key] += value;
4. Find Max Value
int max_val = 0;
for (auto &[key, value] : m)
max_val = max(max_val, value);
int max_key = -1;
for (auto &[key, value] : m)
if (value > max_val) {
max_val = value;
max_key = key;
}
5. Sorting a Map by Values
vector<pair<int, int>> v(m.begin(), m.end());
sort(v.begin(), v.end(), [](auto &a, auto &b) {
return a.second > b.second;
});
6. Erasing Elements
m.erase(2);
for (auto it = m.begin(); it != m.end(); ) {
if (it->second < 10)
it = m.erase(it);
else
++it;
}
7. map vs unordered_map
map: Ordered, O(log n)
unordered_map: Unordered, O(1) avg
C++ Map Usage Guide
8. Checking Key Existence
if (m.count(5)) { /* exists */ }
if (m.find(5) != m.end()) { /* exists */ }
Summary Cheat Sheet
m[key] = value;
m[key] += 1;
m.erase(key);
m.count(key);
m.find(key);
for (auto &[k, v] : m)
cout << k << " " << v;
sort by value:
vector<pair<int, int>> v(m.begin(), m.end());
sort(v.begin(), v.end(), [](auto &a, auto &b) {
return a.second > b.second;
});