Home > Article > Backend Development > How to Remove Elements from a Vector by Value in C ?
How to Remove Vector Elements By Value in C
Consider the vector myVector containing the values {5, 9, 2, 8, 0, 7} in order. To erase the element holding the value "8" through its position, one could use:
myVector.erase(myVector.begin() + 4); // Erase the 4th element
Alternatively, to erase based on the value "8" directly, one can utilize the std::remove() function:
#include <algorithm> int main() { std::vector<int> vec{5, 9, 2, 8, 0, 7}; vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end()); return 0; }
In this case, std::remove() reorders the elements, moving "8" to the end of the vector, and then erase() effectively removes the moved element. This approach is known as the "erase-remove idiom."
The above is the detailed content of How to Remove Elements from a Vector by Value in C ?. For more information, please follow other related articles on the PHP Chinese website!