removing std::list elements, how to do it right ?

Started by
11 comments, last by Zahlman 18 years, 3 months ago
Instead of letting Update() "remove itself from the list" (update shouldn't even *know* about the list), instead return a boolean indicating whether or not to erase the value. Then you can check the result in the loop like

if (it->Update()) {  it = numbers.erase(it);} else {  ++it;}


But at this point, it makes more sense to make use of remove_if:

// First a little setup work...struct Updater {  bool operator()(const Thing& t) {    return t.Update();  }};std::list<Thing> myThings;// ...// This line doesn't need to be changed if you change to a different container :Dstd::erase(std::remove_if(myThings.begin(), myThings.end(), Updater()), myThings.end());
Advertisement
Thank you,but it is not the solution I was looking for. We still use the loop, and remove elements there. But if the elements should be removed elsewhere ? Not in this loop. How to do it then ?
That's what I'm saying: you can *re-arrange things* so that they *are* removed here.

This topic is closed to new replies.

Advertisement