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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-18 00:11:02747browse

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);

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());

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!

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