Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over std::vector with lambda does not want to remove with remove_if

I have a small problem with lambda expression while using remove_if on std::vector

I have a following piece of code :

    std::remove_if( openList.begin(), openList.end(), 
        [&](BoardNode& i){
            std::cout<< i.getCoordinates() << std::endl;
            std::cout<< currentNode.getCoordinates() << std::endl;
            return i.getCoordinates() == currentNode.getCoordinates(); }
        );

There is no compiler error with this, but the elements which return true from the above statement won't be removed from the vector;

I get printed on the screen e.g.

[5,5]
[5,5]

but the openList remains as it was.

like image 270
Patryk Avatar asked Jan 26 '26 03:01

Patryk


1 Answers

std::remove_if doesn't erase anything from the vector, since it doesn't have access to it. Instead, it moves the elements you want to keep to the start of the range, leaving the remaining elements in a valid but unspecified state, and returns the new end.

You can use the "erase-remove" idiom to actually erase them from the vector:

openList.erase(
    std::remove_if( 
        openList.begin(), 
        openList.end(), 
        [&](BoardNode& i){return i.getCoordinates() == currentNode.getCoordinates();}),
    openList.end());
like image 91
Mike Seymour Avatar answered Jan 28 '26 17:01

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!