Home > Backend Development > C++ > 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
Release: 2024-11-21 05:57:09
Original
964 people have browsed it

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

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!

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