Home > Article > Backend Development > How to Remove Elements from a C Vector by Value?
In C , the erase() method of vectors allows us to remove elements by their position. But what if we want to remove an element based on its value rather than its position?
Consider the following vector:
vector<int> myVector = {5, 9, 2, 8, 0, 7};
To erase the element with a value of "8" using the traditional erase() method, we would do:
myVector.erase(myVector.begin() + 4);
However, to remove an element by value, we can use the std::remove() function:
#include <algorithm> ... myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVector.end());
Here's how it works:
The above is the detailed content of How to Remove Elements from a C Vector by Value?. For more information, please follow other related articles on the PHP Chinese website!