簡體   English   中英

std :: unordered_map插入錯誤

[英]std::unordered_map insertion error

我有以下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的示例。 任何幫助是極大的贊賞。 謝謝,麻煩您了!

映射中的值屬於Item*類型,因此您需要插入Item*而不是Item 這條線

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

應該

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

您不需要取消引用指針:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM