Search code examples
c++c++17erase-remove-idiom

C++ Erase-remove Idiom on non-existant value in vector


I want to remove an element from a vector, but it is not guaranteed that the element exists. I have looked online but found no information regarding how the erase-remove idiom would treat a value that isn't in the container.

My vector is declared as such: (with the members being added/modified in other pars of the code)

std::vector<Person*> _members

I want to create a remove method inside a class Group containing _members as an attribute to attempt removal of a given person from the group.

I currently am going with: (where person to remove is a pointer to a Person object)

_members.erase(std::remove(_members.begin(), _members.end(), person_to_remove), _members.end());

How will this handle attempting to remove a Person which is not in the vector ? Ideally I would also like to return a boolean to confirm whether the removal has been successful or not, is there a way to do so with my current implementation ?


Solution

  • How will this handle attempting to remove a Person which is not in the vector ?

    Erase-Remove idiom handles correctly non present element (and also multiple elements).

    Ideally I would also like to return a boolean to confirm whether the removal has been successful or not, is there a way to do so with my current implementation?

    You might compare size before and after the removal:

    const auto old_size = _members.size();
    _members.erase(std::remove(_members.begin(), _members.end(), person_to_remove),
                   _members.end());
    const bool deleted = old_size != _members.size();