是不可能使用stl map与struct? [英] Is it impossible to use stl map with struct?

查看:170
本文介绍了是不可能使用stl map与struct?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct Node
{
 int a;
 int b;
};

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

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

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



当我试图将一个结构体映射到int时,它给了我一个编译错误。
为什么?
谢谢!

When I tried to map a struct into int, it gave me a compile error. Why? Thank you!

推荐答案

对于可在地图中用作键的事物,您必须能够使用运算符<()来比较它。您需要为您的节点类添加此类运算符:

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 map与struct?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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