【问题标题】:c++: Can't insert a pair<int, MLine*> to an unordered_mapc ++:无法将一对<int,MLine *>插入到unordered_map
【发布时间】:2019-03-12 21:58:41
【问题描述】:

我将 my_map 定义为:

 std::unordered_map<MyAction, MyLine * >;

(MyAction 是一个枚举类)

MyLine 是std::vector&lt;MyPoint&gt;;

MyLines 是std::vector&lt;MyLine&gt;

然后使用以下代码:

for (const auto &myline : mylines) {

            my_map.insert(
                std::pair<MyAction, const Myline *>(MyAction::KEEP_1, &myline));

我收到以下错误:

my_utility.cpp:85:33: error: no matching member function for call to 'insert'
            my_map.insert(
            ~~~~~~~~~~~~~~~~~~~~^~~~~~
my_project/external/clang/darwin/include/c++/v1/unordered_map:909:26: note: candidate function not viable: no known conversion from 'pair<my_namespace::MyAction, const Myline *>' to 'const pair<const std::__1::unordered_map<my_namespace::MyAction, std::__1::vector<math::Vector3<double>, std::__1::allocator<math::Vector3<double> > > *, std::__1::hash<my_namespace::MyAction>, std::__1::equal_to<my_namespace::MyAction>, std::__1::allocator<std::__1::pair<const MyAction, std::__1::vector<math::Vector3<double>, std::__1::allocator<math::Vector3<double> > > *> > >::key_type, std::__1::unordered_map<my_namespace::MyAction, std::__1::vector<math::Vector3<double>, std::__1::allocator<math::Vector3<double> > > *, std::__1::hash<my_namespace::MyAction>, std::__1::equal_to<my_namespace::MyAction>, std::__1::allocator<std::__1::pair<const MyAction, std::__1::vector<math::Vector3<double>, std::__1::allocator<math::Vector3<double> > > *> > >::mapped_type>' for 1st argument
    pair<iterator, bool> insert(const value_type& __x)
                         ^

知道出了什么问题吗?谢谢!

【问题讨论】:

  • 你正在抛弃 constness。无序地图包含MyLine*,但您正在尝试插入const MyLine*
  • 如果我需要在 for 循环中使用 const auto & 如何避免这种情况?
  • @Edamame:你不能。您需要在循环中使用auto&amp;,或创建新的MyLine 对象。或者你可以让地图保持const MyLine *

标签: c++ pointers unordered-map


【解决方案1】:

您的地图有MyLine *,但在插入函数中您还写了const。删除它,它应该可以工作。

【讨论】:

  • 如果我删除了插入中的 const,我收到错误消息说 clang/darwin/include/c++/v1/utility:422:5: 注意:候选构造函数不可行:第二个参数 (' const std::__1::vector<:vector3>, std::__1::allocator<:vector3> > > *') 将丢失 const 限定符 pair(_T1 const& __t1, _T2 const& __t2 ) . -> 我认为这是因为在 for 循环中我使用了 const auto & ,但我确实需要这样做
  • @Edamame 如果你有这个对象并且你不能修改它,你应该让你的无序地图保持const MyLine*
猜你喜欢
  • 1970-01-01
  • 2012-06-20
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2013-08-10
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多