如何使用for_each删除STL映射中的每个值?

stu*_*ith 7 c++ algorithm boost stl

假设我有一个STL映射,其中值是指针,我想将它们全部删除.我如何表示以下代码,但是使用std :: for_each?我很高兴使用Boost的解决方案.

for( stdext::hash_map<int, Foo *>::iterator ir = myMap.begin();
     ir != myMap.end();
     ++ir )
{
  delete ir->second; // delete all the (Foo *) values.
}
Run Code Online (Sandbox Code Playgroud)

(我发现了Boost checked_delete,但我不确定如何将其应用于pair<int, Foo *>迭代器所代表的).

(另外,出于这个问题的目的,忽略存储需要在STL容器中删除的原始指针的事实并不是很明智).

注意:我随后在下面找到并列出了一个单行答案......但是代码非常糟糕,所以我接受了GMan的理智答案.

GMa*_*ckG 14

你必须创建一个函数对象:

struct second_deleter
{
    template <typename T>
    void operator()(const T& pX) const
    {
        delete pX.second;
    }
};

std::for_each(myMap.begin(), myMap.end(), second_deleter());
Run Code Online (Sandbox Code Playgroud)

如果你正在使用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));
Run Code Online (Sandbox Code Playgroud)

但您可以尝试自动执行此操作的指针容器库.

请注意,您没有使用地图,而是使用地图hash_map.我建议你切换到更新的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;
};
Run Code Online (Sandbox Code Playgroud)

并使用它像:

typedef wrapped_container<
            boost::unordered_map<int, Foo*>, second_deleter> my_container;

my_container.container./* ... */
Run Code Online (Sandbox Code Playgroud)

这确保无论如何,您的容器将通过删除器进行迭代.(例如,例外情况.)

相比:

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
Run Code Online (Sandbox Code Playgroud)