问题描述
我已尝试编写此代码:
#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制作一个tetris游戏)。
无论如何,问题是一行语法错误,我说:global_map [pos] =home;。
我没有得到错误的原因,我在这里发布谁需要更多的细节:
In truth this isn't the original code, but a version simplified of it (I' am trying to make a tetris game with OpenGL).
Anyway the problem is a syntax error on the line where I say: "global_map[pos]="home";".
I don't get the reason of the error, and I post it here for who needs more details:
invalid operands to binary expression (' position const' and 'position const')
推荐答案
对于关联容器的要求, std :: map
是其中之一,是元素之间必须有一个排序用作键。默认情况下,这是 std :: less
,它只是调用 operator<
。所以你需要做的使用 struct
作为 std :: map
中的键是实现 operator 。
The requirement for associative containers, which std::map
is one of, is that there must be an ordering between the elements used as keys. By default, this is std::less
which simply calls operator <
. So all you need to do to use your struct
as a key in a std::map
is implement operator <
for it.
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 );
}
这篇关于不能使用struct作为地图的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!