Suppose I have a STL map where the values are pointers, and I want to delete them all. How would I represent the following code, but making use of std::for_each? I’m happy for solutions to use Boost.
for( stdext::hash_map<int, Foo *>::iterator ir = myMap.begin();
ir != myMap.end();
++ir )
{
delete ir->second; // delete all the (Foo *) values.
}
(I’ve found Boost’s checked_delete, but I’m not sure how to apply that to the pair<int, Foo *> that the iterator represents).
(Also, for the purposes of this question, ignore the fact that storing raw pointers that need deleting in an STL container isn’t very sensible).
Note: I have subsequently found and listed a one-line answer below… but the code is pretty awful so I’ve accepted GMan’s saner answer.
You have to make a function object:
If you’re using boost, you could also use the lambda library:
But you might try the pointer containers library which does this automatically.
Note you are not using a map, but a
hash_map. I recommend you switch to boost’sunordered_map, which is more current. However, there doesn’t seem to be aptr_unordered_map.For safety, you should wrap this thing up. For example:
And use it like:
This ensures no matter what, your container will be iterated through with a deleter. (For exceptions, for example.)
Compare: