我可以定义一个关键字是结构的地图吗? [英] Can I define a map whose key is a structure?

查看:83
本文介绍了我可以定义一个关键字是结构的地图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

您可以使用任何类型作为地图键,只要它实现了一个运算符< (加上存储在容器中的值的通常的拷贝和分配要求)。



例如:

  struct example {int x; } 

bool operator< (const example& l,const example& r){return l.x& r.x; }

std :: map< example,int>值;

或者,您可以提供比较函数作为地图模板的第三个参数, c $ c> operator 。有关详情,请此处(参数比较)。 / p>

and how can I do it in C++?

解决方案

You can use any type as a map key, as long as it implements an operator< (plus the usual copy-and-assign requirements for values stored in containers).

For instance:

struct example { int x; }

bool operator < (const example &l, const example &r) { return l.x < r.x; }

std::map<example, int> values;

Alternatively, you may provide a comparison function as the third argument of the map template instead of defining operator<. More details here (parameter Compare).

这篇关于我可以定义一个关键字是结构的地图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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