Using erase-remove_if idiom

Say I have one std::vector<std::pair<int,Direction>>.

I am trying to use erase-remove_if to remove pairs from a vector.

stopPoints.erase(std::remove_if(stopPoints.begin(),
                                stopPoints.end(),
                                [&](const stopPointPair stopPoint)-> bool { return stopPoint.first == 4; }));

I want to remove all pairs whose .first value is set to 4.

In my example, I have pairs:

- 4, Up
- 4, Down
- 2, Up
- 6, Up

However, after executing the erase-remove_if function, I left:

- 2, Up
- 6, Up
- 6, Up

What am I doing wrong here?

+4
source share
2 answers

The correct code is:

stopPoints.erase(std::remove_if(stopPoints.begin(),
                                stopPoints.end(),
                                [&](const stopPointPair stopPoint)-> bool 
                                       { return stopPoint.first == 4; }), 
                 stopPoints.end());

You need to remove the range starting with the iterator returned from std::remove_ifthe end of the vector, and not just one element.

"Why?"

  • std::remove_ifswap elements around the vector to add all elements that do not match the predicate at the beginning of the container .

    • , .

    • std::vector::erase , , , , .


: (Wikipedia).

+10

std::vector::erase :

iterator erase( const_iterator pos );
iterator erase( const_iterator first, const_iterator last );

pos, [first, last).

last , , , std::remove_if. :

stopPoints.erase(std::remove_if(stopPoints.begin(),
                                stopPoints.end(),
                                [&](const stopPointPair stopPoint)-> bool { return stopPoint.first == 4; }), 
                 stopPoints.end());

erase-remove : , {2, 4, 3, 6, 4}, 4:

std::vector<int> vec{2, 4, 3, 6, 4};
auto it = std::remove(vec.begin(), vec.end(), 4);

{2, 3, 6, A, B}, "" ( A B ( ), 6 ) A ( "" ).

:

vec.erase(it)

std::vector::erase , it, A {2, 3, 6, B}.

:

vec.erase(it, vec.end())

, it vec.end(), A, B .

+5

Source: https://habr.com/ru/post/1651678/


All Articles