Home > Backend Development > C++ > How Do I Remove Elements with a Specific Value from an STL Vector?

How Do I Remove Elements with a Specific Value from an STL Vector?

DDD
Release: 2024-11-19 02:59:03
Original
237 people have browsed it

How Do I Remove Elements with a Specific Value from an STL Vector?

Removing Elements with a Specific Value from an STL Vector

In the context of STL vector operations, it may come as a surprise that there's no explicit method to remove elements based on their values. This common operation can be achieved using different approaches.

Using std::remove

The std::remove function serves as a utility method for vector manipulation. It discreetly rearranges the vector's elements, moving the ones that should not be removed to the front. Its return value is an iterator pointing to the element following the last one that has not been removed. This iterator can then be used as an argument to std::erase to permanently eliminate the redundant elements now located at the end of the vector:

std::vector<int> vec;
// Initialize vec with values
int value = n;
vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());
Copy after login

This approach efficiently identifies and removes the specified elements from the vector while maintaining its logical order.

The above is the detailed content of How Do I Remove Elements with a Specific Value from an STL Vector?. 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