Home > Backend Development > C++ > How to Erase Vector Elements by Value in C ?

How to Erase Vector Elements by Value in C ?

Mary-Kate Olsen
Release: 2024-11-08 13:02:02
Original
139 people have browsed it

How to Erase Vector Elements by Value in C  ?

Erasing Vector Elements by Value in C

When working with vectors in C , it's common to need to remove specific elements. Typically, this is done by specifying the position of the element to be erased using erase(myVector.begin() 4). However, there may be instances where you want to erase an element based on its value rather than its position.

To achieve this, C provides the erase-remove idiom, which combines the std::remove() and std::erase() functions. Here's an example of how to implement it:

#include <algorithm>

int main() {
    vector<int> myVector = {5, 9, 2, 8, 0, 7};

    myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVector.end());

    return 0;
}
Copy after login

The std::remove() function takes three arguments: the start and end iterators of the vector and the value to be removed. It modifies the vector by moving all elements with the specified value to the end of the vector, effectively removing them from their original positions.

The std::erase() function then erases the range of elements from the vector. In this example, it erases all elements from the position returned by std::remove() to the end of the vector.

By utilizing the erase-remove idiom, you can conveniently erase elements based on their value, improving the efficiency and maintainability of your code.

The above is the detailed content of How to Erase Vector Elements by Value in C ?. 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