mercredi 3 février 2016

Reset iterator inside loop with erase method

Here's a little piece of code, which is making us a little mad...

for (vector<QSharedPointer<Mine>>::iterator itMine = _mines.begin(); 
       itMine != _mines.end();) {
    auto point2 = shipFire[l].getBulletLine().p2();
    if (_mines[pos]->checkCollision(point2)) { // _mines is a Vector<QSharedPointer<Mine>>
        Explosion explosionMine(_mines[pos]->point());
        _explosions.push_back(explosionMine);
        itMine = _mines.erase(itMine);
        bulletErased = true;
        scoreFrame += 100;
    }
    else {
        ++itMine;
        pos++;
    }
}

Here is the problem, the itMine is erasing two of our vector<..<Mine>> and it's making the program to shutdown unexpectedly

We thought about it, and came up with this : All of our iterators are being invalidated after erasing the one of the Mine, right ?

But we are a little confused about how to change our actual code to fit to the new one ?

The main question is : how do we reset this itr ?

ps : if you have any questions, or if you need a little more of code to understand the logic behind, feel free to ask more question !

Best Regards, and thank you in advance.

Aucun commentaire:

Enregistrer un commentaire