是否不可能将 STL 映射与结构一起用作键? [英] Is it impossible to use an STL map together with a struct as key?

查看:17
本文介绍了是否不可能将 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 映射与结构一起用作键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆