2012-06-29 42 views
2

我有以下unordered_map,它将一个指针映射到类型为int的对象的键类型为int。std :: unordered_map插入错误

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

地图中的值是Item*类型的,所以你需要插入Item*,不Item。这条线

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

应该

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

谢谢!这解决了它。指针仍然让我感到困惑,对于新手的错误感到抱歉。 –

+1

@RMartin:指针的最佳方法是不使用它们_除非你绝对必须。我无法想象你在这里不能使用'std :: unordered_map '。 – ildjarn

2

你不需要取消引用指针:

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

你说得对!谢谢! –