Re: templated deletePointer in for_each algorithm
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));
The third argument of for_each here constructs a temporary object of
type take_second<T> where T is the pair<const int, string *> (the
value_type of the map). As a constructor argument, the deletePointer
function is passed. The functor remembers that function. The for_each
function calls the functor for every pair<> in the map, and the
functor, in turn, selects the second member of the pair and invokes the
remembered function on it.