2

我有以下 unordered_map,它使用 int 类型的键将指针映射到 Item 类型的对象。

typedef std::unordered_map<int, Item*> ItemList;
ItemList Items;

但是,在我的 addItem 方法中,我在编译时收到一个奇怪的错误。

void ItemManager::addItem(Item *it)  {
    int i = it->getItemID();
    Items.insert(ItemList::value_type(i, *it));
}

产量:

item_manager.cc: In member function ‘void ItemManager::addItem(Item*)’:
item_manager.cc:31:51: error: no matching function for call to ‘std::pair<const int, Item*>::pair(int&, Item&)’
item_manager.cc:31:51: note: candidates are:
/usr/include/c++/4.6/bits/stl_pair.h:140:2: note: template<class ... _Args1, class ... _Args2> std::pair::pair(std::piecewise_construct_t, std::tuple<_Args1 ...>, std::tuple<_Args2 ...>)
/usr/include/c++/4.6/bits/stl_pair.h:135:2: note: template<class _U1, class _U2> std::pair::pair(std::pair<_U1, _U2>&&)
/usr/include/c++/4.6/bits/stl_pair.h:131:2: note: template<class _U1, class _U2, class> std::pair::pair(_U1&&, _U2&&)
/usr/include/c++/4.6/bits/stl_pair.h:125:2: note: template<class _U2, class> std::pair::pair(const _T1&, _U2&&)
/usr/include/c++/4.6/bits/stl_pair.h:120:2: note: template<class _U1, class> std::pair::pair(_U1&&, const _T2&)
/usr/include/c++/4.6/bits/stl_pair.h:112:17: note: constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const int, _T2 = Process*, std::pair<_T1, _T2> = std::pair<const int, Process*>]
/usr/include/c++/4.6/bits/stl_pair.h:112:17: note:   candidate expects 1 argument, 2 provided
/usr/include/c++/4.6/bits/stl_pair.h:108:21: note: template<class _U1, class _U2> constexpr std::pair::pair(const std::pair<_U1, _U2>&)
/usr/include/c++/4.6/bits/stl_pair.h:103:26: note: constexpr std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = const int, _T2 = Process*]
/usr/include/c++/4.6/bits/stl_pair.h:103:26: note:   no known conversion for argument 2 from ‘Process’ to ‘Process* const&’
/usr/include/c++/4.6/bits/stl_pair.h:99:26: note: constexpr std::pair<_T1, _T2>::pair() [with _T1 = const int, _T2 = Process*]
/usr/include/c++/4.6/bits/stl_pair.h:99:26: note:   candidate expects 0 arguments, 2 provided

任何想法可能导致这些错误?我是 C++ 新手,所以我一直在研究我在网上找到的 unordered_maps 示例。任何帮助是极大的赞赏。谢谢,麻烦您了!

4

2 回答 2

4

地图中的值属于类型Item*,因此您需要插入Item*,而不是Item。这条线

 Items.insert(ItemList::value_type(i, *it));

应该

Items.insert(ItemList::value_type(i, it));
于 2012-06-29T17:25:45.643 回答
2

您不需要取消引用指针:

void ItemManager::addItem(Item *it)  {
    int i = it->getItemID();
    Items.insert(ItemList::value_type(i, it));
}
于 2012-06-29T17:25:22.127 回答