C++ Erase Vector Element By Value Rather Than By Position?


Answer :

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.


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); 

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.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?