jeudi 1 novembre 2018

C++ erase if exist

I want to remove element from container with an idempotent approach (i.e, if the element exist, then remove it, otherwise do nothing, and I can do this as many time as I want and the outcome is the same)

As far a I know, doing map::erase is idempotent, even the key is no exist it's also safe. I think set is the same.

Then what about vector (and similair linear container)? I know this works well:

auto it = std::find(vec.begin(), vec.end(), val);

if (it != vec.end())
  vec.erase(it);

But I'm wondering if there is any approach that we don't have to check it == vec.end() manually?

According to cpp document, the behavior of vec.erase(vec.end()) is not defined, which means we can not do vec.erase(std::find(..)). Is there any method will do this check for me so that I can do remove_if_exist with one line code?

Aucun commentaire:

Enregistrer un commentaire