C++ Erase vector element by value rather than by position?

C++VectorStlEraseErase Remove-Idiom

C++ Problem Overview


vector<int> myVector;

and lets say the values in the vector are this (in this order):

5 9 2 8 0 7

If I wanted to erase the element that contains the value of "8", I think I would do this:

myVector.erase(myVector.begin()+4);

Because that would erase the 4th element. But is there any way to erase an element based off of the value "8"? Like:

myVector.eraseElementWhoseValueIs(8);

Or do I simply just need to iterate through all the vector elements and test their values?

C++ Solutions


Solution 1 - C++

How about std::remove() instead:

#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

This combination is also known as the erase-remove idiom.

Solution 2 - C++

You can use std::find to get an iterator to a value:

#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
    myVector.erase(position);

Solution 3 - C++

You can not do that directly. You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());. See this erasing elements from vector for more details.

Solution 4 - C++

Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.

#include <iostream>
#include <range/v3/all.hpp>

int main(int argc, char const *argv[])
{
    std::vector<int> vi{2,4,6,8,10};
    for (auto& i : vi) {
        std::cout << i << std::endl;
    }
    std::cout << "-----" << std::endl;
    std::vector<int> vim = vi | ranges::view::remove_if([](int i){return i == 8;});
    for (auto& i : vim) {
        std::cout << i << std::endl;
    }
    return 0;
}

outputs

>2
>4
>6
>8
>10
>-----
>2
>4
>6
>10

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJake WilsonView Question on Stackoverflow
Solution 1 - C++Georg FritzscheView Answer on Stackoverflow
Solution 2 - C++zneakView Answer on Stackoverflow
Solution 3 - C++NaveenView Answer on Stackoverflow
Solution 4 - C++kometenView Answer on Stackoverflow