我们可以在STL映射中使用用户定义的类作为键吗? [英] Can we use a user defined class for the key in a STL map?

查看:136
本文介绍了我们可以在STL映射中使用用户定义的类作为键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在地图中的一个键,但是,我发现它应该是多个数据。我可以将这些数据放在一个用户定义的类中,并把整个类作为一个键在地图中吗?

I need a key in the map, however, I found it should be multiple data. Can I put these data in one user defined class and put the whole class as a key in the map?

它会影响时间效率吗?

这里应该应用什么其他问题?

What other concerns should be applied here?

推荐答案

任何类型都可以用作键


  • 可复制

  • 可分配

  • Comparable,因为地图按键排序

如果你的类只是一个简单的结构,那么它已经可以复制和赋值。对于类是可比较的,你必须实现 operator ,或者使用自定义比较函数创建地图来使用。

If your class is just a simple structure, then it's already copyable and assignable. For a class to be comparable, you must either implement operator<, or create the map with a custom comparison function to use instead.

对时间效率的唯一影响来自更大的对象需要更长的时间来复制和比较。如果对象需要是那个大小,那么你不能做任何事情,所以不要担心。

The only impact on time efficiency comes from larger objects taking longer to copy and compare. If the objects need to be that size, then there's nothing you can do about that, so don't worry about it.

这篇关于我们可以在STL映射中使用用户定义的类作为键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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