1

I have map where individual Colors are mapped to multiple Entities.

I want to erase all elements from the map with given value e passed as an argument:

std::map<Color, Entity> encodedColors;

void eraseAllByValue(Entity e) {
     for (auto it = encodedColors.begin(); it != encodedColors.end();) {
        if (it->second == e) {
            it = encodedColors.erase(it);
        } else {
            ++it;
        }
    }
}

The above function works just fine, however: how can this be achieved with std::for_each or similiar STL construct? I am having problem with creating correct Lambda expression.

weno
  • 804
  • 8
  • 17
  • 2
    Checkout the example of [`std::remove`](https://en.cppreference.com/w/cpp/algorithm/remove) or search for _erase remove idom_. – Timo Apr 06 '20 at 14:29
  • 2
    C++20 offers [`std::erase_if`](https://en.cppreference.com/w/cpp/container/map/erase_if) for this, before that your solution is as good as it can be: [remove_if equivalent for std::map](https://stackoverflow.com/questions/800955/remove-if-equivalent-for-stdmap) – Yksisarvinen Apr 06 '20 at 14:34
  • 1
    @Timo erase-remove idiom is great, except for containers on which you cannot use remove – Yksisarvinen Apr 06 '20 at 14:43
  • 2
    The `std::map` and similar containers are the odd-balls when it comes to erasure, since the programmer had to write hand-rolled `for` loops, as opposed to calling an algorithm function. I'm surprised this wasn't addressed earlier than C++20. – PaulMcKenzie Apr 06 '20 at 14:55

0 Answers0