Erasing Vector Elements by Value in C
When working with vectors in C , it's common to need to remove specific elements. Typically, this is done by specifying the position of the element to be erased using erase(myVector.begin() 4). However, there may be instances where you want to erase an element based on its value rather than its position.
To achieve this, C provides the erase-remove idiom, which combines the std::remove() and std::erase() functions. Here's an example of how to implement it:
#include <algorithm> int main() { vector<int> myVector = {5, 9, 2, 8, 0, 7}; myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVector.end()); return 0; }
The std::remove() function takes three arguments: the start and end iterators of the vector and the value to be removed. It modifies the vector by moving all elements with the specified value to the end of the vector, effectively removing them from their original positions.
The std::erase() function then erases the range of elements from the vector. In this example, it erases all elements from the position returned by std::remove() to the end of the vector.
By utilizing the erase-remove idiom, you can conveniently erase elements based on their value, improving the efficiency and maintainability of your code.
The above is the detailed content of How to Erase Vector Elements by Value in C ?. For more information, please follow other related articles on the PHP Chinese website!