Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Erase vector element by value rather than by position? [duplicate]

vector<int> myVector; 

and lets say the values in the vector are this (in this order):

5 9 2 8 0 7 

If I wanted to erase the element that contains the value of "8", I think I would do this:

myVector.erase(myVector.begin()+4); 

Because that would erase the 4th element. But is there any way to erase an element based off of the value "8"? Like:

myVector.eraseElementWhoseValueIs(8); 

Or do I simply just need to iterate through all the vector elements and test their values?

like image 977
Jake Wilson Avatar asked Aug 02 '10 05:08

Jake Wilson


People also ask

How do I remove a specific value from a vector?

The erase() function can remove an element from the beginning, within, or end of the vector. In order to remove all the elements from the vector, using erase(), the erase() function has to be repeated the number of times there are elements, beginning from the first element.

Can you use delete [] on a vector?

Yes, but it does not go without constraints. There are two ways of deleting a vector.


2 Answers

How about std::remove() instead:

#include <algorithm> ... vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end()); 

This combination is also known as the erase-remove idiom.

like image 101
Georg Fritzsche Avatar answered Sep 23 '22 21:09

Georg Fritzsche


You can use std::find to get an iterator to a value:

#include <algorithm> std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8); if (position != myVector.end()) // == myVector.end() means the element was not found     myVector.erase(position); 
like image 42
zneak Avatar answered Sep 19 '22 21:09

zneak