0

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 ?

A.D
  • 427
  • 1
  • 4
  • 12
  • The `remove` call returns an iterator to the first element that matches the value to be removed. If there is no such value, it will return `_members.end()`, and then the call to `erase` will erase no elements. – Marshall Clow Apr 29 '20 at 14:25

1 Answers1

6

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();
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • So it just deletes it if it finds it and (?) does nothing if the element is not present ? I am curious to know how it handles it concretely. – A.D Apr 29 '20 at 14:28
  • *"Basically"*, `std::remove` moves element to delete at the end, then we erase the (potentially empty) range of deleted elements. – Jarod42 Apr 29 '20 at 14:32
  • So here nothing would be moved right ? Or would it therefore be more efficient to first check if it exists and then only delete it if it does ? – A.D Apr 29 '20 at 14:33
  • 2
    If no element would be removed, then nothing is moved, and erase does nothing. The 2 option are linear and similar. – Jarod42 Apr 29 '20 at 14:42
  • Coming back to this I am wondering: what if the vector was empty and we tried to remove something from it ? Would there need to be some specific sort of check first ? – A.D Apr 30 '20 at 07:51
  • 1
    `std::remove` will iterate empty range and return `end()` as no elements to erase. Then `erase` will delete empty range (so no-op) from empty range. All is fine. – Jarod42 Apr 30 '20 at 08:09