我试过写这段代码:
#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;
}
事实上这不是原始代码,而是它的简化版本(我正在尝试使用 OpenGL 制作俄罗斯方 block 游戏)。
无论如何,问题是我说的行中的语法错误:“global_map[pos]="home";"。
我不明白错误的原因,我将其发布在这里以供需要更多详细信息的人使用:
invalid operands to binary expression (' position const' and 'position const')
最佳答案
关联容器的要求,std::map
是其中之一,是用作键的元素之间必须有一个顺序。默认情况下,这是 std::less
它只是调用 operator <
.所以你需要做的就是使用你的 struct
作为 std::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 );
}
关于c++ - 不能将结构用作 map 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10905716/