Re: templated deletePointer in for_each algorithm
Kaz Kylheku wrote:
shaun wrote:
for_each(myVec.begin(),myVec.end(),printPointer);
cout<<endl;
//Now: how to delete a map of pointers using for_each?
By defining a functor which binds the function to the pair->second.
First, write this class:
template <class PAIR>
class take_second {
typedef void (*func_type)(typename PAIR::second_type &);
func_type func;
public:
take_second(func_type f) : func(f) { }
void operator()(PAIR &p)
{
func(p.second);
}
};
Now, you can do this:
for_each(myMap.begin(), myMap.end(),
take_second<map<int, string
*>::value_type>(deletePointer));
And now, one more improvement. Hide this all with a new flavor of the
for_each function which knows that it's supposed to iterate over the
second field:
template <class ITER, class FUNC>
void for_each_second(ITER begin, ITER end, FUNC func)
{
for_each(begin, end, take_second<typename ITER::value_type>(func));
}
Now you can write:
for_each_second(myMap.begin(), myMap.end(),
deletePointer<string>);
It would be nice if take_second didn't have the restriction that it
wraps an ordinary C++ function; that is, if it could transparently wrap
either a functor or a regular C++ function.