I would like to drop a number of elements from a map based on some condition:
#include <unordered_map>
#include <ranges>
#include <iostream>
int main() {
std::unordered_map<int, int> numbers = {{1,2}, {2,1}, {3,2}, {4,5}};
auto even = [](auto entry){return entry.second %2 == 0;};
for(auto& [key, val] : numbers | std::views::filter(even)) {
numbers.erase(val);
}
for(auto& [key, val] : numbers) {
std::cout << key << " " << val << "\n";
}
}
But it seems there I am invalidating iterators that the range-based loop needs:
4 5
3 2
1 2
I know how to do this explicitly using iterators, but is there a nice and concise range-based way to delete elements based on a filter?