你必须创建一个函数对象:
struct second_deleter
{
template <typename T>
void operator()(const T& pX) const
{
delete pX.second;
}
};
std::for_each(myMap.begin(), myMap.end(), second_deleter());
如果你使用 boost,你也可以使用 lambda 库:
namespace bl = boost::lambda;
std::for_each(myMap.begin(), myMap.end(), second_deleter(),
bl::bind(bl::delete_ptr(),
bl::bind(std::select2nd<myMap::value_type>(), _1));
但您可以尝试使用自动执行此操作的 pointer containers 库。
请注意,您使用的不是地图,而是hash_map。我建议你切换到 boost 的unordered_map,它更流行。不过好像没有ptr_unordered_map。
为了安全起见,你应该把这东西包起来。例如:
template <typename T, typename Deleter>
struct wrapped_container
{
typedef T container_type;
typedef Deleter deleter_type;
wrapped_container(const T& pContainer) :
container(pContainer)
{}
~wrapped_container(void)
{
std::for_each(container.begin(), container.end(), deleter_type());
}
T container;
};
并像这样使用它:
typedef wrapped_container<
boost::unordered_map<int, Foo*>, second_deleter> my_container;
my_container.container./* ... */
这确保无论如何,您的容器都将使用删除器进行迭代。 (例如,例外情况。)
比较:
std::vector<int*> v;
v.push_back(new int);
throw "leaks!"; // nothing in vector is deleted
wrapped_container<std::vector<int*> > v;
v.container.push_back(new int);
throw "no leaks!"; // wrapped_container destructs, deletes elements