Home > Backend Development > C++ > How to Efficiently Remove Elements by Value from an STL Vector?

How to Efficiently Remove Elements by Value from an STL Vector?

Patricia Arquette
Release: 2024-11-18 00:11:02
Original
821 people have browsed it

How to Efficiently Remove Elements by Value from an STL Vector?

Efficient Value Removal from STL Vector

Despite the extensive functionalities provided by the STL vector class, it lacks an explicit function to expunge elements based on their values. This operation, however, is commonly encountered.

Solution: Employing std::remove

STL offers the std::remove function, which doesn't explicitly remove elements but relocates elements to be retained to the beginning of the container. It returns an iterator pointing past these retained elements:

auto new_end = std::remove(vec.begin(), vec.end(), int_to_remove);
Copy after login

To complete the removal, we can use vec.erase to eliminate the excess elements now located at the end:

vec.erase(new_end, vec.end());
Copy after login

This approach effectively purges elements with the target value while preserving the vector's contiguous structure.

The above is the detailed content of How to Efficiently Remove Elements by 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template