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

2022-01-24 00:00:00 dictionary containers c++ stl stdmap

我有以下代码:

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.

相关文章