user3334986
user3334986

Reputation: 155

Finding a specific item in a list

First of all, I know that a vector would be much easier for this. However, this is for a class and the list helps with sorting. Now, I have a list of pointers to Sprite objects. I would like to start with the second item in the list and run some methods on them but I'm not sure how to start with the 2nd item, and also how to access the Sprites functions from within the list.

Here is the code in question.

    list<Sprite*>::iterator iter = sprites.begin();
    iter++;
    iter++;
    while (iter != sprites.end())               //Missile Movement
    {
        dynamic_cast<Missile*>(sprites[iter])->Update();

        if (!dynamic_cast<Missile*>(sprites[iter])->GetActive())
        {
            delete sprites[iter];
            sprites.erase(iter--);
        }

        iter++;
    }

Currently the code is set up to use a vector of Sprite pointers. I cannot use the current code to call Update or GetActive on the objects. Can you guys help me understand how to change the syntax to change sprites to a list?

Upvotes: 0

Views: 61

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106196

list<Sprite*>::iterator iter = sprites.begin();
if (sprites.size() < 2) throw std::runtime_error("too few sprites");
iter++;
iter++;
while (iter != sprites.end())               //Missile Movement
{
    if (Missile* p = dynamic_cast<Missile*>(*iter))
    {
        p->Update();
        if (!p->GetActive())
        {
            delete p;
            iter = sprites.erase(iter);
        }
        else
            ++iter;
    }
    else
        std::cerr << "WARN: sprite is not a missile\n";
}

Upvotes: 2

sj0h
sj0h

Reputation: 912

Instead of using index notation sprites[iter], just dereference the iterator, as *iter.

Also, the erase() call will give problems, as the object has been destroyed by the time it is post-decremented. Instead use the return value such as iter = sprites.erase(iter); and the decrementing if you need to for your logic.

Upvotes: 0

Related Questions