不能使用结构作为地图的索引

Ram*_*uri 1 c++ map

我试过写这段代码:

#include <iostream>
#include <map>

using namespace std;

typedef struct 
{
    int x;
    int y;
}position;

int main(int argc, char** argv)
{
    map<position, string> global_map;
    position pos;
    pos.x=5;
    pos.y=10;
    global_map[pos]="home";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

事实上,这不是原始代码,而是简化了它的版本(我正在尝试用OpenGL制作一个俄罗斯方块游戏).
无论如何,问题是我说的行上的语法错误:"global_map [pos] ="home";".
我没有得到错误的原因,我在这里发布了谁需要更多细节:

invalid operands to binary expression (' position const' and 'position const')
Run Code Online (Sandbox Code Playgroud)

K-b*_*llo 6

对于要求关联容器,这std::map是之一,是必须有用作键元件之间的次序.默认情况下,这std::less只是调用operator <.因此,您需要做structstd::map就是operator <将它作为密钥用于实现它.

struct position
{
    int x;
    int y;
};

bool operator <( position const& left, position const& right )
{
    return left.x < right.x || ( left.x == right.x && left.y < right.y );
}
Run Code Online (Sandbox Code Playgroud)