Home  >  Article  >  Backend Development  >  How to Remove Elements from a C Vector by Value?

How to Remove Elements from a C Vector by Value?

DDD
DDDOriginal
2024-11-14 22:21:02722browse

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.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn