This question already has an answer here:
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?
How about
std::remove()
instead:This combination is also known as the erase-remove idiom.
You can use
std::find
to get an iterator to a value:Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.
outputs
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 useerase
function. Something like:myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());
. See this erasing elements from vector for more details.