lundi 27 février 2017

C++ List Iteration and erasing

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

Aucun commentaire:

Enregistrer un commentaire