DuskFall
DuskFall

Reputation: 422

Use Object in vector in loop

Currently, i have a loop iterating through a vector, and i'm trying to find the index of an object, while i'm in the loop, to delete it. How can i go about this?

Here's my code :

for (Object &a : objectDict)
    {
        a.setTime(theTime);

        double tempMoveX = 0, tempMoveZ = 0, tempUX = 0,tempUZ = 0;

        for (Object &b : objectDict)
        {
            if (a != b)
            {
                ...
                    debug << fixed << setprecision(20) <<  "Collision" << endl;
                    a.appendMass(b.getMass());

                    objectDict.erase(find(objectDict.begin(), objectDict.end(), b));
                ...

Thats the important part. How can i erase object b from the vector?

Upvotes: 0

Views: 83

Answers (2)

John Zwinck
John Zwinck

Reputation: 249103

One easy way is to simply build a separate vector containing the indexes of elements to erase later. Once you've finished going through the regular vector, loop in reverse order through the "to be removed" vector (in reverse because you don't want to invalidate the indexes as you go), and erase them.

Alternatively, as you iterate over the original vector, select the elements you want to keep, and copy them to another vector. At the very end, swap the two vectors (which is cheap). This will work better if you have relatively many elements to delete, on average.

Upvotes: 1

LihO
LihO

Reputation: 42083

Well, in case you need an index while iterating vector's elements, instead of:

for (Object &a : objectDict) { ...

do traditional:

for (size_t i = 0; i < objectDict.size(); ++i) { ...

and within the loop's body: instead of using reference a, you'll use objectDict[i], then when you will need to erase element, you can do:

objectDict.erase(vec.begin() + i);
i--;

i-- is used to move the index backwards by 1 so that when the next iteration increments it again, the element that follows right after the element that has been erased is not skipped.

Upvotes: 0

Related Questions