JuniorCodeCommonNot answered yet
Remove entries with even values from unordered_map and print their keys
Given a std::unordered_map<int, int>, remove every entry whose value is even and print the key of each removed entry.
Requirements:
- Do not erase while iterating with a plain range-for (that invalidates the iterator).
- Output order is not guaranteed for an
unordered_map.
#include <unordered_map>
void removeEvenValues(std::unordered_map<int, int>& m) {
// your code here
}
Write the implementation.
You cannot erase from a container while iterating with a range-for loop — this invalidates the iterator. Safe approaches: collect keys to erase, then erase in a separate pass; or use the C++20 std::erase_if helper which handles this cleanly.
- ✗Erasing inside a range-for — undefined behaviour because the iterator is invalidated
- ✗Using
map.erase(it)without capturing the returned next iterator in a manual loop - ✗Not knowing about
std::erase_if(C++20) which is the cleanest solution
- →What is iterator invalidation and which containers are most/least prone to it?
- →How does
erasereturn the next valid iterator in most containers?
Contents
Task
Remove all entries with even values from an unordered_map and print the removed keys.
Key points
- Never erase inside a range-for — iterator invalidation → UB.
erase(it)returns the next valid iterator — use it in a manual loop.std::erase_if(C++20) is the cleanest solution.
Contents