我在这里编写了一个自定义删除器来删除单个 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::pair
上delete
,这根本不是一个指针。我猜你想删除
std::pair
的第二个成员,即A*
,你应该更改Deleter
到:
struct Deleter
{
template <typename K, typename V>
void operator () (std::pair<K, V>& p)
{
delete p.second;
}
};
关于c++ - map 删除器在 C++ 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36697461/