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

How to Erase Vector Elements Based on Value in C ?

DDD
Release: 2024-11-08 08:21:02
Original
1047 people have browsed it

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
Copy after login

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

myVector.erase(myVector.begin() + 4);
Copy after login

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());
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template