gpt4 book ai didi

c++ - 是否不可能将 STL 映射与结构一起用作键?

转载 作者:IT老高 更新时间:2023-10-28 22:32:17 26 4
gpt4 key购买 nike

我有以下代码:

struct Node
{
int a;
int b;
};

Node node;
node.a = 2;
node.b = 3;

map<int, int> aa;
aa[1]=1; // OK.

map<Node, int> bb;
bb[node]=1; // Compile error.

当我尝试将结构 Node 的实例映射到 int 时,出现编译错误。为什么?

最佳答案

要使某事物可用作 map 中的键,您必须能够使用 operator<() 对其进行比较.您需要将这样的运算符添加到您的节点类中:

struct Node
{
int a;
int b;

bool operator<( const Node & n ) const {
return this->a < n.a; // for example
}
};

当然,真正的操作符做什么取决于比较对你的结构的实际意义。

关于c++ - 是否不可能将 STL 映射与结构一起用作键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2214295/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com