tags:

views:

181

answers:

3
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.eraseElementWhosValueIs(8);

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

A: 

You can not do that directly. You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());. See this erasing elements from vector for more details.

Naveen
+1  A: 

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

#include <algorithm>
std::vector<int>::iterator position = std::find(vector.begin(), vector.end(), 8);
if (position != vector.end()) // == vector.end() means the element was not found
    myVector.erase(position);
zneak
+6  A: 

How about std::remove() instead:

vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());
Georg Fritzsche
How does it affect the vector itself? Documentation says it returns an iterator to the new end of the range. I suppose the vector itself will not be aware of the changes?
zneak
Since `std::remove` returns an iterator pointing to the "new end" of the retained elements, this should be used: `myVector.resize(std::remove(myVector.begin(), myVector.end(), 8) - myVector.begin())`
rwong
@zne: Yes, the vector still has to be adjusted. Added that.
Georg Fritzsche
I'm a bit confused... It appears this would erase elements from the vector from the element that I'm looking to erase, all the way to the end of the vector... Am I incorrect? All I want is that one element removed.
Jakobud
@jak: Take a look at the description of `remove()`: It moves all values not equal to the value passed to the beginning of the range `[begin,end)`. With your example in the question you'd get `5,9,2,0,7,7`. As `remove()` however returns an iterator to the new end, `vec.erase()` can remove the obsolete elements (i.e. the second `7` here) if that is needed.
Georg Fritzsche
Interesting, thanks!
Jakobud