map deleter是不是在C ++中工作?

时间:2016-04-18 14:52:28

标签: c++ dictionary stl

我在这里编写了一个自定义删除工具来删除单个地图元素。但它不起作用。我知道我可以使用唯一指针解决此问题。但我想知道如何在地图中做到这一点。

#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
class A 
{ 
    int i;
    public: 
    A() { }
    A(int pi = 0):i(pi)   {  cout<<"A()\n"; }
    void show() const { cout<<i<<endl; }
    ~A()   {  cout<<"~A()\n"; }
};
struct Deleter
{
    template <typename T>
    void operator () (T *ptr)
    {
         delete ptr;
    }
};
int main()
{
    map<char, A *> mymap;
    mymap['a'] =  new A(30);
    mymap['b'] =  new A(20);
    mymap['c'] =  new A(10);
    map<char, A *>::iterator it;
    for(it = mymap.begin(); it != mymap.end() ; it++)
        it->second->show();
    for_each(mymap.begin(),mymap.end(),Deleter());
    return 0;
}

显示编译时错误。

In file included from /usr/include/c++/4.9/algorithm:62:0,
                 from 4:
/usr/include/c++/4.9/bits/stl_algo.h: In instantiation of '_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = std::_Rb_tree_iterator<std::pair<const char, A*> >; _Funct = Deleter]':
32:49:   required from here
/usr/include/c++/4.9/bits/stl_algo.h:3755:14: error: no match for call to '(Deleter) (std::pair<const char, A*>&)'
  __f(*__first);
              ^
15:8: note: candidate is:
18:10: note: template<class T> void Deleter::operator()(T*)
18:10: note:   template argument deduction/substitution failed:
In file included from /usr/include/c++/4.9/algorithm:62:0,
                 from 4:
/usr/include/c++/4.9/bits/stl_algo.h:3755:14: note:   mismatched types 'T*' and 'std::pair<const char, A*>'
  __f(*__first);
              ^

5 个答案:

答案 0 :(得分:1)

当错误消息被抱怨时,您正试图在deletestd::pair,这根本不是指针。我想你想delete成为std::pair的第二位成员,即A*,你应该将Deleter更改为:

struct Deleter
{
    template <typename K, typename V>
    void operator () (std::pair<K, V>& p)
    {
         delete p.second;
    }
};

LIVE

答案 1 :(得分:0)

您假设std::map::iterator::operator*返回    值,但实际上返回std::pair<const char,A*>&

工作代码: http://coliru.stacked-crooked.com/a/e18bd4600575d39a

答案 2 :(得分:0)

映射迭代器迭代键和值对。你必须重写你的删除器才能接受这样一对:

struct Deleter {
    template<typename K, typename T>
    void operator() (std::pair<typename K, typename T> &p) {
       delete p.second;
    }
}

答案 3 :(得分:0)

  

模板参数扣除/替换失败:[...]
  注意:不匹配的类型'T *'和'std :: pair'     __f(* __第一);

似乎已经足够了:你期待一个指针,但是for_each会给你一个,简单来说就是这样。

__f(*__first);  // notice *

所以make:

struct Deleter
{
    template <typename T>
    void operator () (T pair)
    {
         delete pair.second;
    }
};

答案 4 :(得分:0)

删除者访问该对,所以你想要:

struct Deleter
{
    template <typename T>
    void operator () (T p)
    {
         delete p.second;
    }
};