1

I want to delete object from vector which has property set on specific value. In this example:

void RemoveUser(int val)
{
    users.remove_if([val](User u)
    {
        return u.val == val;
    });
}

I can remove specific user based on its val property. This works on std::list, but its not working on std::vector. How can I archieve same result on vector?

1 Answers1

4

std::vector doesn't have a remove_if member. But there is a standard algorith, aptly named std::remove_if that can work in tandem with the vectors erase member function.

users.erase(remove_if(begin(users), end(users), [val](User const& u)
{
    return u.val == val;
}), end(users));

First remove_if shifts the elements of the range, and returns an iterator past the end of all the "good ones". The vector is of the same size as when we started at this point. Now that iterator is fed to erase, which kills all of those items, from that "new end", to the "old end" of the vector.

The reason std::list implements its own member version of remove_if is to better utilize its node based structure. It doesn't have to do copies to shift elements around or delete them. For std::vector, the algorithm is the best we can do.

Nejc Galof
  • 2,538
  • 3
  • 31
  • 70
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • It is an important distinction. I've seen code that does stuff like call `delete` on the "bad" elements after a call to `remove_if`. – juanchopanza Feb 26 '18 at 21:56
  • @juanchopanza - That implies the code was using raw pointers as owning handles. I think misunderstanding `remove_if` was the least of the problems there. – StoryTeller - Unslander Monica Feb 26 '18 at 21:58
  • Sigh. OK, then take the bad elements to do anything else with their value. Remove tables from a database or whatever. – juanchopanza Feb 26 '18 at 22:00
  • @juanchopanza - No need for dramatics. Already reworded given how sticky a point it is. If the vectors elements don't tidy after themselves when moved, don't go blaming algorithms that assume value semantics. – StoryTeller - Unslander Monica Feb 26 '18 at 22:02