c++ - map 删除器在 C++ 中不起作用?

标签 c++ dictionary stl

我在这里编写了一个自定义删除器来删除单个 map 元素。但它不起作用。我知道我可以使用 unique pointer 解决这个问题。但我想知道如何在 map 中做到这一点。

#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);
              ^

最佳答案

正如错误消息所提示的那样,您正试图在 std::pairdelete,这根本不是一个指针。我猜你想删除 std::pair 的第二个成员,即A*,你应该更改Deleter 到:

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

LIVE

关于c++ - map 删除器在 C++ 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36697461/

相关文章:

c++ - 模板接受 const 但不接受文字

c++ - 异步函数调用的参数生命周期

C#字典,如何获取特定值

swift - TableView 中的单元格不显示信息。 swift

类中的 C++ std::vector,函数在返回值和大小在 foreach 中增长时崩溃

c++ - 正则表达式每两个字符拆分字符串

c++ - 将函数中的排序数字写入文本文件?

python - 如何从 Python 中的字典中提取所有值?

c++ - std::vector 的后代是否可以合并和排序?

c++ - 从 vector 集中修剪非公共(public)元素