Home  >  Article  >  Backend Development  >  How to Remove Elements with a Specific Value from an STL Vector?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-21 05:57:09920browse

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

Erasing Elements with Specific Value from stl Vector

STL vectors are popular containers in C , but their API lacks a method for removing elements based on their values. This prompts the question:

How can an item be removed from an stl vector based on its value?

Despite the absence of a dedicated method in the vector class, there's a solution using standard library functions.

Solution:

Use the std::remove function, which doesn't directly remove elements from the container but instead rearranges them. It moves elements that should not be removed to the beginning of the container and returns an iterator pointing to the next element after them.

To complete the removal process, pass this iterator to container_type::erase, which actually removes the extra elements now located at the end of the container. Here's an example:

std::vector<int> vec;
// Populate the vector...
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());

This code first uses std::remove to identify and move elements not to be removed to the beginning of the vector. Then, vec.erase is invoked to permanently remove these extra elements from the container.

The above is the detailed content of How to Remove Elements with a Specific 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