首頁  >  文章  >  後端開發  >  如何按值從 C 向量中刪除元素?

如何按值從 C 向量中刪除元素?

DDD
DDD原創
2024-11-14 22:21:02723瀏覽

How to Remove Elements from a C++ Vector by Value?

Removing Vector Elements by Value in C++

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:

  • std::remove() takes three arguments: the start and end iterators of the vector and the value to be removed.
  • It returns an iterator pointing to the element after the last removed element.
  • The erase() method is then used to remove the elements from the iterator returned by std::remove() to the end of the vector.

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn