【问题标题】:Error while inserting item to std::map将项目插入 std::map 时出错
【发布时间】:2018-03-25 12:09:39
【问题描述】:

我正在尝试简单地将新项目插入到具有自定义键和值类型的地图中:

struct Address {
    bool operator<(const Address& a) const { return 1; }
};
struct Cell {};

std::map<Address, Cell> map;
map.insert(std::make_pair<Address, Cell>(Address(), Cell()));

G++ 编译得很好,但我的 IDE (CLion) 抱怨插入方法的参数(用红色下划线标记为错误):参数类型不匹配:Class 'std::pair

' 与类 'std::initializer_list<:map main::cell>>::value_types>'
不兼容。

为什么会出现此错误?我的代码有问题吗?还是 IDE 中的错误?

【问题讨论】:

  • @juanchopanza 谢谢,你是对的。我简化了问题。
  • 您能否 1) 指定您使用的是什么编译器? 2)发布完整的例子 3)尝试重现是在godbolt上? The code is compiling 对于我在 Godbolt 上尝试的每个编译器
  • 或者你的意思是它用红色强调它?他们使用的解析器可能不完整,您应该仅用作提示。这里的权限是实际的编译器,而不是 IDE。尝试编译,看看是否有效。
  • @IlyaPopov 是的,IDE 用红色强调它,仅此而已。就像我写的那样,它编译得很好——我只是想问一下代码中是否存在编译器不会提及(IDE 会提及)的“隐藏错误”,或者是 CLion 中的一些错误。
  • 请不要将std::make_pair 与明确指定的模板参数一起使用。此函数旨在从其函数参数中推断其模板参数,如下所示:std::make_pair(Address{}, Cell{})。如果要指定类型,只需使用std::pair&lt;Address, Cell&gt;{}。当您以这种方式使用 std::make_pair 时,您可能会遇到奇怪的问题,尤其是左值。

标签: c++ dictionary clion


【解决方案1】:

您可以使用std::vector 而不是std::map width a std::pair
要解决问题更改:

std::map<Address, Cell> map;

到:

std::vector<std::pair<Address, Cell> > map;

并包含向量库

#include <vector>

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 2010-09-10
    • 2014-06-01
    相关资源
    最近更新 更多