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:
以上是如何按值從 C 向量中刪除元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!