[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: Using std::set but need to change an element



steve wrote:
Actually, I figured it out:

    for (ArbIter arb = arbiters.begin(); arb != arbiters.end(); ++arb)
    {
        // Erase key from set, modify it, then add it again.
        Arbiter newArb = *arb;
        arbiters.erase(arb);
        newArb.PreStep(inv_dt);
        arbiters.insert(newArb);
        //(*arb).PreStep(inv_dt);
    }


Er, the code above wasn't quite right.

I had to change the two for loops in World.cpp into while loops. arbiters.erase(arb) would invalidate the iterator otherwise.

    while (arb != arbiters.end())
    {
        // Erase key from set, modify copy, then add it again.
        Arbiter newArb((*arb).body1, (*arb).body2);
        newArb.PreStep(inv_dt);
        arbiters.erase(arb++);
        arbiters.insert(newArb);
    }

The above code works, and I got it straight from Effective STL by Scott Meyers.

It turns out that the Standard is not specific on whether sets should or should not have immutable members. The above example of modifying members in a set is the safest and most portable way to to do so.

I managed to get the original example to run, but only after trying to figure out how to get GLUT working on my system. Still, I am now satisfied that the code is correct, and I plan to use it in my own code which simply uses SDL anyway.

--
GBGames' Blog, An Indie Game Developer's Somewhat Interesting Thoughts:
http://www.gbgames.com/blog
Staff Reviewer for Game Tunnel, the Independent Underground:
http://www.gametunnel.com