Home  >  Article  >  Backend Development  >  How to Erase Vector Elements Based on Value in C ?

How to Erase Vector Elements Based on Value in C ?

DDD
DDDOriginal
2024-11-08 08:21:021016browse

How to Erase Vector Elements Based on Value in C  ?

Erasing Vector Elements Based on Value in C

The issue arises when attempting to erase a vector element based on its value rather than its position. Consider a vector with the following values:

5 9 2 8 0 7

Typically, we might erase the fourth element containing the value "8" using this code:

myVector.erase(myVector.begin() + 4);

However, is there a more direct way to erase an element by its value?

std::remove() to the Rescue

The std::remove() function comes into play here. It removes elements from a range that match a specific value. Combined with erase(), we can use the erase-remove idiom to achieve our goal:

#include <algorithm>

...

myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVector.end());

This combination iterates through the vector, removes all instances of "8," and then erases the modified range. The resulting vector now contains:

5 9 2 0 7

The above is the detailed content of How to Erase Vector Elements Based on Value in C ?. 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