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 << [Link] << " " << [Link] << 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([Link](), [Link]());
sort([Link](), [Link](), [](auto &a, auto &b) {
return [Link] > [Link];
});
6. Erasing Elements
[Link](2);
for (auto it = [Link](); it != [Link](); ) {
if (it->second < 10)
it = [Link](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 ([Link](5)) { /* exists */ }
if ([Link](5) != [Link]()) { /* exists */ }
Summary Cheat Sheet
m[key] = value;
m[key] += 1;
[Link](key);
[Link](key);
[Link](key);
for (auto &[k, v] : m)
cout << k << " " << v;
sort by value:
vector<pair<int, int>> v([Link](), [Link]());
sort([Link](), [Link](), [](auto &a, auto &b) {
return [Link] > [Link];
});