2

Ok, I've run into this issue multiple times and thought it would be nice to throw this out to the good people on SO.

Say I have made a class, lets call it Resource. So the Resource class has a boolean variable which indicates weather any instance is active or not.

Now, I create a container which holds references to objects of the Resource type.

Over time , some of them get deactivated and I want to delete these deactivated objects so that they free up memory. Invariably I try to do this by : trying to iterate over the elements in the container and deleting the ones flagged as inactive. This , obviously leads to problems with iterator invalidation and the program starts throwing runtime errors.

So finally, my question is , what is the best method to safely delete objects depending on some condition that can only be evaluated by looking into the contents of the object.

3

2 Answers 2

4

Use the erase-remove idiom with std::remove_if. E.g.:

std::vector<int> myvec; ... myvec.erase(std::remove_if(myvec.begin(),myvec.end(), [] (int i) -> bool { return false; }), myvec.end()); 
Sign up to request clarification or add additional context in comments.

2 Comments

What about associative containers like maps ? std::remove_if doesnt work for them I gather.
@angryInsomniac: no it doesn't work because it would break ordering. This question provides an answer for that problem.
0

The safest method is to use std::remove_if. This will move all items that match the given predicate to the end of the sequence. You can then delete them.

2 Comments

What about associative containers like maps ?
With a map you can delete the element an iterator points to without invalidating any other iterators. That means you can do your_map.erase(it++);. See this question for more information.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.