【问题标题】:std::unordered_map insertion errorstd::unordered_map 插入错误
【发布时间】:2012-06-29 17:22:12
【问题描述】:

我有以下 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 示例。任何帮助是极大的赞赏。请,谢谢!

【问题讨论】:

    标签: c++ insert c++11 compiler-errors unordered-map


    【解决方案1】:

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

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

    应该是

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

    【讨论】:

    • @RMartin :指针的最佳方法是不要使用它们,除非你绝对必须这样做。我无法想象你不能在这里使用std::unordered_map&lt;int, Item&gt;
    【解决方案2】:

    你不需要取消引用指针:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-20
      • 2016-09-19
      相关资源
      最近更新 更多