Use a range-based for with structured bindings (C++17): for (const auto& [key, value] : m) visits every entry of a std::map in sorted key order without copying it. Write auto& [key, value] to change the values. Before C++17, loop over const auto& entry and read entry.first and entry.second.
Every element of a std::map is a std::pair<const Key, Value>, and a loop over the map visits those pairs from the smallest key to the largest. Most questions about iterating a map come down to naming the two halves of that pair, avoiding a copy of each one, and not breaking the loop when the map changes under it. The sections below cover structured bindings, iterators and .first/.second, keys or values alone, erasing while you loop, std::unordered_map, and a range of keys, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1Range-based for with structured bindingsRecommended
Since C++17, auto [a, b] unpacks a pair into two names, so the loop header says what each half means. Take the entry by const auto& to read it in place; plain auto would copy every key and value. Drop the const and the value name refers to the value inside the map, so assigning to it updates the map. The order comes from the map's comparator: ascending by default, descending with std::greater<>.
#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> stock{{"pear", 4}, {"apple", 7}, {"fig", 0}}; // Structured bindings (C++17) name the key and the value of each entry. // const auto& reads each entry in place, with no copy. for (const auto& [fruit, count] : stock) { std::cout << fruit << ": " << count << '\n'; } // auto& (no const) lets the loop change the values in the map for (auto& [fruit, count] : stock) { count += 10; } std::cout << "after restock: apple=" << stock["apple"] << " fig=" << stock["fig"] << '\n'; // The key is const even here: fruit = "kiwi"; would not compile, // because changing a key would break the map's sort order // A std::map with std::greater iterates from the largest key down std::map<int, std::string, std::greater<>> ranks{ {1, "gold"}, {3, "bronze"}, {2, "silver"}}; for (const auto& [place, medal] : ranks) { std::cout << place << '=' << medal << ' '; } std::cout << '\n'; }
Output
The map was filled as pear, apple, fig, but it prints apple: 7, fig: 0, pear: 4: a std::map always iterates in key order, never in insertion order. The second loop adds 10 to each value through auto&, giving after restock: apple=17 fig=10. The key stays const even then, because changing it in place would break the sort order; to rename a key, see the FAQ. With std::greater<> as the third template argument the same loop prints 3=bronze 2=silver 1=gold, largest key first.
2Iterators, .first and .second
Without structured bindings, the loop variable is the pair itself and you read .first (the key) and .second (the value). The explicit iterator loop is still the tool when you need the iterator: to compare it with the end, to erase through it, or to walk backwards with rbegin() and rend(). The example ends with the most common hidden mistake: writing out the pair type and forgetting that the key is const.
#include <iostream> #include <map> #include <string> #include <utility> int main() { std::map<std::string, int> ages{{"Ada", 36}, {"Linus", 28}, {"Grace", 45}}; // Before C++17: each element is a std::pair, read .first and .second for (const auto& entry : ages) { std::cout << entry.first << " is " << entry.second << '\n'; } // The explicit iterator loop, still needed when you need the iterator for (auto it = ages.begin(); it != ages.end(); ++it) { std::cout << it->first << (std::next(it) != ages.end() ? ", " : "\n"); } // Backwards with reverse iterators for (auto it = ages.rbegin(); it != ages.rend(); ++it) { std::cout << it->first << ' '; } std::cout << '\n'; // Trap: the element type is std::pair<const std::string, int>. // Spelled without the const, the reference binds to a temporary // copy of each entry, so it does not see changes to the map. for (const std::pair<std::string, int>& p : ages) { ages[p.first] = 99; std::cout << "copy sees " << p.second << '\n'; break; } for (const auto& p : ages) { // auto gets the type right ages[p.first] = 100; std::cout << "reference sees " << p.second << '\n'; break; } }
Output
entry.first and entry.second give Ada is 36, Grace is 45, Linus is 28, in key order. With the iterator in hand, std::next(it) tells the last entry apart, so the names print as Ada, Grace, Linus, and the reverse iterators print Linus Grace Ada. The last two loops change the map and then read the loop variable. Spelled as std::pair<std::string, int>, the reference binds to a converted copy of each entry, so it prints copy sees 36 after the map was set to 99, and every step copied a string. With auto the reference is the entry itself: reference sees 100. Let auto name the type, or write std::map<K, V>::value_type.
3Only the keys or only the values
std::map has no keys() or values() member, but C++20's std::views::keys and std::views::values show one half of each pair without copying anything. They work in a range-based for, compose with other views such as std::views::reverse, and their begin()/end() fill a vector. Before C++20, loop over the pairs and use the half you need, or hand .second to an algorithm through a lambda.
#include <iostream> #include <map> #include <numeric> #include <ranges> #include <string> #include <vector> int main() { std::map<std::string, double> prices{ {"tea", 2.5}, {"cake", 4.0}, {"coffee", 3.0}}; // C++20: views::keys and views::values look at one half of each pair for (const auto& name : std::views::keys(prices)) { std::cout << name << ' '; } std::cout << '\n'; double total = 0; for (double p : prices | std::views::values) { total += p; } std::cout << "total: " << total << '\n'; // Copy the keys into a vector (C++20 has no ranges::to; that is C++23) auto keys = std::views::keys(prices); std::vector<std::string> names(keys.begin(), keys.end()); std::cout << names.size() << " names, first: " << names.front() << '\n'; // Views compose: the values, largest key first for (double p : prices | std::views::reverse | std::views::values) { std::cout << p << ' '; } std::cout << '\n'; // Without views: std::accumulate over the pairs, adding .second double sum = std::accumulate( prices.begin(), prices.end(), 0.0, [](double acc, const auto& kv) { return acc + kv.second; }); std::cout << "sum: " << sum << '\n'; }
Output
The keys come out sorted, cake coffee tea, and the values sum to total: 9.5. Copying the keys view gives 3 names, first: cake; in C++23 that copy is one call, std::ranges::to<std::vector>(), but this page compiles as C++20. Reversing before taking the values prints 2.5 3 4, the prices of tea, coffee and cake. std::accumulate over the pairs gets the same sum: 9.5 in any standard.
4Erasing entries while iterating
Erasing an entry invalidates the iterators to that entry only. So the safe loop takes the iterator that erase(it) returns, which points at the next entry, and advances with ++it only when it erased nothing. A range-based for cannot do this, because its iterator is hidden. C++20 wraps the whole loop in one call: std::erase_if(map, predicate), which also returns how many entries it removed.
#include <iostream> #include <map> #include <string> void print(const std::map<std::string, int>& m) { for (const auto& [k, v] : m) { std::cout << k << '=' << v << ' '; } std::cout << '\n'; } int main() { std::map<std::string, int> stock{ {"apple", 0}, {"fig", 3}, {"kiwi", 0}, {"pear", 5}}; // erase(it) returns the iterator to the next entry: use it, // and only advance with ++it when nothing was erased for (auto it = stock.begin(); it != stock.end();) { if (it->second == 0) { it = stock.erase(it); } else { ++it; } } print(stock); // C++20: std::erase_if does the same loop for you std::map<std::string, int> scores{ {"amy", 91}, {"bob", 48}, {"cy", 77}, {"dee", 32}}; auto removed = std::erase_if(scores, [](const auto& entry) { return entry.second < 50; }); std::cout << "removed " << removed << ": "; print(scores); // Wrong: stock.erase(it) inside a range-for loop leaves the loop's // hidden iterator dangling, and the next ++ is undefined behaviour }
Output
The loop drops the two entries at zero and leaves fig=3 pear=5. std::erase_if removes the scores under 50 and prints removed 2: amy=91 cy=77. The old idiom m.erase(it++) works too, since the increment happens before the erase, but it = m.erase(it) reads more plainly and is the same pattern used for vectors and lists. Inserting while you iterate a std::map does not invalidate any iterator, but whether the loop reaches the new entry depends on where its key sorts, so collect the additions and insert them after the loop.
5std::unordered_map and a stable order
Every loop above works unchanged on a std::unordered_map, but there the order is unspecified: it follows the hash buckets, can differ between compilers, and can change after an insert that grows the table. That is fine for sums and lookups. For output a person reads, or a test compares, copy the entries into something ordered first: a std::map for key order, or a vector of pairs sorted by value.
#include <algorithm> #include <iostream> #include <map> #include <string> #include <unordered_map> #include <utility> #include <vector> int main() { std::unordered_map<std::string, int> visits{ {"home", 120}, {"blog", 45}, {"docs", 300}, {"about", 45}}; // The same loop works on unordered_map, but the order is unspecified: // it depends on the hash and the bucket count, so never rely on it. int total = 0; for (const auto& [page, n] : visits) { total += n; } std::cout << visits.size() << " pages, " << total << " visits\n"; // Sorted by key: copy into a std::map (or sort a vector of keys) std::map<std::string, int> by_name(visits.begin(), visits.end()); for (const auto& [page, n] : by_name) { std::cout << page << ' '; } std::cout << '\n'; // Sorted by value: copy the pairs into a vector and sort that, // breaking ties on the key so the order is always the same std::vector<std::pair<std::string, int>> rows(visits.begin(), visits.end()); std::sort(rows.begin(), rows.end(), [](const auto& a, const auto& b) { if (a.second != b.second) { return a.second > b.second; // most visits first } return a.first < b.first; }); for (const auto& [page, n] : rows) { std::cout << page << ' ' << n << '\n'; } }
Output
The first loop only adds, so its order does not matter: 4 pages, 510 visits. Copied into a std::map, the pages print as about blog docs home. The vector sorted by value prints docs 300 and home 120 first, and the tie on 45 is broken by name, about 45 before blog 45. Without that tie-break, std::sort may put equal values in either order. The same copy-and-sort is how you sort a std::map by value: a map can only ever be ordered by its key.
6Part of a map: lower_bound, upper_bound, equal_range
Because a std::map is sorted, you can loop over a slice of keys without visiting the rest. lower_bound(a) finds the first key that is not less than a, upper_bound(b) the first key greater than b, and the iterators between them cover the closed range from a to b. A std::multimap holds several values under one key, and equal_range(key) returns the pair of iterators around all of them.
#include <iostream> #include <map> #include <string> int main() { std::map<int, std::string> events{ {1990, "web"}, {1995, "java"}, {1998, "c++98"}, {2011, "c++11"}, {2020, "c++20"}}; // Only the keys in [1995, 2011]: lower_bound is the first key >= 1995, // upper_bound the first key > 2011, so the loop stops before 2020 auto first = events.lower_bound(1995); auto last = events.upper_bound(2011); for (auto it = first; it != last; ++it) { std::cout << it->first << ' ' << it->second << '\n'; } // A multimap keeps several values per key; equal_range gives them all std::multimap<std::string, std::string> tags{ {"cpp", "maps"}, {"go", "slices"}, {"cpp", "ranges"}, {"cpp", "views"}}; auto [from, to] = tags.equal_range("cpp"); for (auto it = from; it != to; ++it) { std::cout << it->second << ' '; } std::cout << '\n'; // A plain loop over a multimap visits every key once per value for (const auto& [lang, tag] : tags) { std::cout << lang << ':' << tag << ' '; } std::cout << '\n'; }
Output
The bounds pick 1995 java, 1998 c++98 and 2011 c++11, and stop before 2020 without looking at it. For the cpp key, equal_range gives maps ranges views, in the order they were inserted, which a multimap keeps for equal keys. A plain loop over the multimap visits each key once per value: cpp:maps cpp:ranges cpp:views go:slices. Both lookups take logarithmic time, so this is much faster than testing every key in a loop.
7Which should you use?
| Method | Verdict | Standard | Best for |
|---|---|---|---|
| for (const auto& [k, v] : m) | Default | C++17 | Reading every entry |
| for (auto& [k, v] : m) | Default | C++17 | Changing values in place |
| entry.first / entry.second | Older code | C++11 | Code that must build before C++17 |
| for (auto it = m.begin(); …) | When needed | Any | Erasing, std::next, rbegin() for reverse order |
| std::views::keys / values | Good | C++20 | One half of each pair, no copies |
| std::erase_if(m, pred) | Good | C++20 | Removing entries by a condition |
| lower_bound / upper_bound | When needed | Any | A range of keys, or a multimap via equal_range |
Frequently asked questions
Does std::map keep insertion order?
No. A std::map is always sorted by key, using std::less unless you pass another comparator, and iterates in that order whatever order you inserted in. A std::unordered_map has no meaningful order at all. To keep insertion order, store the entries in a std::vector<std::pair<K, V>>, or keep a vector of keys next to the map and loop over that.
Should I write auto, auto& or const auto& in a loop over a map?
Write const auto& to read, and auto& to change values. Plain auto (also as auto [k, v]) copies every key and value into the loop variable, which costs a string copy per entry and means writes go to the copy, not the map. Avoid spelling the type as const std::pair<std::string, int>&: the element type is std::pair<const std::string, int>, so that reference silently binds to a temporary copy.
How do I erase from a std::map while iterating over it?
Use an iterator loop and let erase move it on: for (auto it = m.begin(); it != m.end();) { if (cond) it = m.erase(it); else ++it; }. In C++20, std::erase_if(m, [](const auto& e) { return cond; }) does the same and returns the number removed. Do not call m.erase on the current entry inside a range-based for: the loop then increments an invalidated iterator, which is undefined behaviour.
How do I sort a std::map by value?
You cannot reorder the map itself; it is always ordered by key. Copy the entries into a std::vector<std::pair<K, V>> and std::sort it with a lambda that compares .second, adding a tie-break on .first if equal values must come out in a fixed order. If the values are unique and you only need them sorted, inserting them as keys of a second map works too.
How do I change a key while iterating over a std::map?
Keys are const because the map depends on their order, so you cannot assign to one. Since C++17 you can move an entry to a new key without copying its value: auto node = m.extract(it); node.key() = "new"; m.insert(std::move(node));. Do it outside the loop over the same map (collect the iterators or keys first), since the renamed entry may sort ahead of where the loop is.
Why does my map get new entries while I loop and look things up?
m[key] inserts a default value when the key is missing, so looking up keys of one map in another with [] adds entries, and a const map does not allow [] at all. To look up without inserting, use m.find(key) and compare with m.end(), m.contains(key) (C++20) to test, or m.at(key), which throws std::out_of_range for a missing key.