Search code examples
c++listc++11erase

C++ List Iteration and erasing


EDIT: This question refers specifically to std::lists - other similar questions on Stack Overflow refer to std::vectors

I'm using C++ and having trouble erasing an element from a std::list while iterating through it. I have a list of a custom class ('Objects' for the sake of this question), and my code looks like this:

for(auto i : Objects)
    if(i.EraseFlag == true)
        {
            i = Objects.erase(i);
        }

I'm getting the error: 'no matching function for call to std::list::erase(Object&)'

I believe this is the right way (as of C++11) to iterate through lists, erase an element and return an iterator that takes into account the erasure, but clearly I'm doing something wrong. Previously when using vectors I would use 'Objects.erase(Objects.begin() + i)' with i being an integer in a for loop, but given the access requirements of lists this won't work.

Help appreciated.

Thanks


Solution

  • Member function erase deals with iterators.

    For such a task it would be correctly to use an ordinary for loop. For example

    for ( auto it = Objects.begin(); it != Objects.end(); )
    {
        if ( it->EraseFlag ) it = Objects.erase( it );
        else ++it;
    }
    

    Another approach is to use member function remove_if. For example

    Objects.remove_if( []( const auto &value ) { return value.EraseFlag; } );