C++错误: map.insert(make_pair(struct, vector<struct>));

C++ error: map.insert(make_pair(struct, vector<struct>));

本文关键字:struct vector lt gt pair 错误 map insert make C++      更新时间:2023-10-16

下面的代码是国际象棋游戏的一部分,其中键是棋子的位置,值是棋子具有的可能移动

#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;
};

Thos代码将我带到文件"stl_function.h"中的第235行

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

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