【发布时间】:2019-03-12 21:58:41
【问题描述】:
我将 my_map 定义为:
std::unordered_map<MyAction, MyLine * >;
(MyAction 是一个枚举类)
MyLine 是std::vector<MyPoint>;
MyLines 是std::vector<MyLine>;
然后使用以下代码:
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&,或创建新的MyLine对象。或者你可以让地图保持const MyLine *
标签: c++ pointers unordered-map