Ben
Ben

Reputation: 16641

Remove object from std::list

In the following situation, how can I remove the screen from the list?

class ScreenManager {

    list<GameScreen> screens;

    void removeScreen(GameScreen & screen) {
        //screens.remove(screen); // won't work
        //screens.erase( remove( screens.begin(), screens.end(), screen ), screens.end() );  // won't work either
    }
}

Upvotes: 1

Views: 5229

Answers (3)

Johannes S.
Johannes S.

Reputation: 4626

std::remove (or std::list::remove in your case) uses the comparison operator ( operator==) to find/identify the object that should be remove from the container.

Since you use a user-defined type GameScreen, you need to provide operator== for your class. So, in your class you need to implement:

bool operator==( const GameScreen& other ) const  {
    // do whatever you need to determine whether 
    // `GameScreen` instance `other` is equal (in value) 
    // to `this` instance of `GameScreen`
}

Then, screens.remove( screen); will work.

Upvotes: 11

Jacob B
Jacob B

Reputation: 2015

std::list's erase method takes an iterator you want to remove. So once you get an iterator to your screen, just pass it to screens.

In other words, you want to do screens.erase(std::find(screens.begin(), screens.end(), screen)); This will only work if you have operator== correctly defined on your value class.

Note that if you plan to delete things a lot, you might want to use something like std::map instead of std::list (since looking up your screen in the list will be O(n).)

Upvotes: 2

DRVic
DRVic

Reputation: 2481

Use list::find to locate an iterator to the screen you actually want to remove. Then use remove, passing it the iterator.

Upvotes: 2

Related Questions