Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

c++ - Erasing item in a for(-each) auto loop

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...