Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a way to erase specific elements when using a auto variable in a for loop like this?

for(auto a: m_Connections)
{
    if(something)
    {
        //Erase this element

    }
}

I know I can either do say

for(auto it=m_map.begin() ...

or

for(map<int,int>::iterator it=m_map.begin() ...

and manually increment the iterator (and erase) but if I could do it with less lines of code I'd be happier.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
461 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can't. A range-based loop makes a simple iteration over a range simpler, but doesn't support anything that invalidates either the range, or the iterator it uses. Of course, even if that were supported, you couldn't efficiently erase an element without access to the iterator.

You'll need an old-school loop, along the lines of

for (auto it = container.begin(); it != container.end();) {
    if (something) {
        it = container.erase(it);
    } else {
        ++it;
    }
}

or a combination of container.erase() and std::remove_if, if you like that sort of thing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...