patterncppCritical
C++ Erase vector element by value rather than by position?
Viewed 0 times
erasethanelementvectorratherpositionvalue
Problem
vector myVector;and lets say the values in the vector are this (in this order):
5 9 2 8 0 7If 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?
Solution
How about
This combination is also known as the erase-remove idiom.
std::remove() instead:#include
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());This combination is also known as the erase-remove idiom.
Code Snippets
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());Context
Stack Overflow Q#3385229, score: 581
Revisions (0)
No revisions yet.