c++ - 不能将结构用作 map 的索引

标签 c++ dictionary

我试过写这段代码:

#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/

相关文章:

c++ - 命名空间.GetItemFromId 异常

python - 行作为字典 - pymssql

python - 有什么比 dict() 更快的吗?

C# 字典问题

arrays - swift 可编码 : Array of Dictionaries

c++ - 为什么 ofstream::write 在文件末尾添加额外的字节?

c++ - 我在 C++ 中为单链表编写了 operator*。当我编写 main 中包含的函数时,它可以工作,但是当我调用该函数时,它不会

C++ 预处理器不知道模板参数?

c++ - 无法在命令提示符下使用 GCC 构建 WxWidgets

c++ - 从多个 map<key,value> 中搜索的最佳方式是什么?