【问题标题】:C++ error: map.insert(make_pair(struct, vector<struct>)); [duplicate]C++ 错误:map.insert(make_pair(struct, vector<struct>)); [复制]
【发布时间】:2016-07-16 05:08:58
【问题描述】:

以下代码是我正在制作的国际象棋游戏的一部分,其中关键是棋子的位置,值是棋子可能的移动

#include<iostream>
#include<map>
#include<vector>

using namespace std;

struct Coordinate{
    int x, y;
};

int main(){
    map<Coordinate, vector<Coordinate>> moves;//map that have an struct as key and a vector of structs as value.
    //There is the error
    moves.insert(make_pair(Coordinate{0,0},//the struct
                               vector<Coordinate>{Coordinate{1,1},//the vector
                                                  Coordinate{2,2},
                                                  Coordinate{3,3}}));
    return 0;
};

这些代码将我带到文件 'stl_function.h' 中的第 235 行

【问题讨论】:

  • &gt; 在哪里?您还需要一个自定义比较器或Coordinate 上的operator&lt;
  • 是的 Vector&lt; 在第 15 行打开但没有关闭...
  • 包含您遇到的错误。
  • 如果你使用[],它可能是可读的
  • movements[ {0,0} ] = { {1,1}, {2,2}, {3,3} };也是如此

标签: c++ c++11


【解决方案1】:

您需要为您的结构提供自定义比较器:

struct Coordinate{
    int x, y;

    constexpr bool operator<(const Coordinate & rhs) const
    {
        return x < rhs.x && y < rhs.y;   
    }
};

【讨论】:

  • 坦克解决了我的问题。我是 C++ 初学者,你能告诉我 rhs 是什么吗?
  • @RobertoJaimes 它代表“右手边”,因为它用于&lt; 比较的右手边。通常将该参数命名为“rhs”或“other”
猜你喜欢
  • 2011-02-13
  • 2012-12-22
  • 1970-01-01
  • 2021-03-12
  • 2021-07-01
  • 2015-04-10
  • 2019-08-12
  • 2017-08-20
  • 1970-01-01
相关资源
最近更新 更多