不能将STL映射与struct一起用作键吗? [英] Is it impossible to use an STL map together with a struct as key?
本文介绍了不能将STL映射与struct一起用作键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
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
时,出现编译错误.为什么?
When I tried to map an instance of my struct Node
to an int
, I got a compile error. Why?
推荐答案
要使某事物可用作地图中的键,您必须能够使用operator<()
对其进行比较.您需要在节点类中添加这样的运算符:
For a thing to be usable as a key in a map, you have to be able to compare it using operator<()
. You need to add such an operator to your node class:
struct Node
{
int a;
int b;
bool operator<( const Node & n ) const {
return this->a < n.a; // for example
}
};
当然,真正的运算符做什么取决于比较实际上对您的结构意味着什么.
Of course, what the real operator does depends on what comparison actually means for your struct.
这篇关于不能将STL映射与struct一起用作键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文