你必须创建一个函数对象:
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));
但你可以尝试指针容器 http://www.boost.org/doc/libs/1_42_0/libs/ptr_container/doc/ptr_map.html自动执行此操作的库。
请注意,您使用的不是地图,而是hash_map
。我建议你切换到boostunordered_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./* ... */
这可以确保无论如何,您的容器都将使用删除器进行迭代。 (例如,对于例外情况。)
Compare:
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