Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterating through a set [duplicate]

I recently changed some code to use a set instead of a vector:

std::set<b2Body *>toDestroy;
//std::vector<b2Body *>toDestroy;

But now I'm not sure how to iterate the set to find objects. This is what I had:

std::vector<b2Body *>::iterator pos2;
    for(pos2 = toDestroy.begin(); pos2 != toDestroy.end(); ++pos2) {
        b2Body *body = *pos2;     
        if (body->GetUserData() != NULL) {
            CCSprite *sprite = (CCSprite *) body->GetUserData();
            [self removeChild:sprite cleanup:YES];
        }
        _world->DestroyBody(body);
    }

What is the equivalent now that toDestroy is a set? Coming from Objective-C so I'm just learning best practices in C++.

EDIT: adding the error message I get:

error: no match for 'operator=' in 'pos2 = toDestroy. std::set<_Key, _Compare, _Alloc>::begin [with _Key = b2Body*, _Compare = std::less<b2Body*>, _Alloc = std::allocator<b2Body*>]()'
like image 379
sol Avatar asked Mar 03 '11 20:03

sol


2 Answers

You need to declare your iterator to be a set iterator:

Change

std::vector<b2Body *>::iterator pos2;

to

std::set<b2Body *>::iterator pos2;
like image 62
JaredC Avatar answered Sep 27 '22 16:09

JaredC


With C++11 you could simply write:

    for(auto pos2:toDestroy)
like image 31
stanislas.b Avatar answered Sep 27 '22 17:09

stanislas.b