Is it impossible to use an STL map together with a struct as key?(是否不可能将 STL 映射与结构一起用作键?)
本文介绍了是否不可能将 STL 映射与结构一起用作键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
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 映射与结构一起用作键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:是否不可能将 STL 映射与结构一起用作键?


基础教程推荐
猜你喜欢
- C++多态 1970-01-01
- 向量<unique_ptr<A>>使用初始化列表 2022-10-23
- 迭代std :: bitset中真实位的有效方法? 2022-10-18
- C语言数组 1970-01-01
- C语言3个整数的数组 1970-01-01
- C++:为什么结构类需要一个虚拟方法才能成为多态? 2022-10-19
- 对 STL 容器的安全并行只读访问 2022-10-25
- 总计将在节日礼物上花多少钱 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 用指数格式表示浮点数 1970-01-01