Can we use a user defined class for the key in a STL map?(我们可以为 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?
推荐答案
任何类型都可以作为key使用
Any type can be used as a key as long as it is
- 可复制
- 可分配
- 具有可比性,因为地图是按键排序的
如果你的类只是一个简单的结构,那么它已经是可复制和可分配的.要使类具有可比较性,您必须实现 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 映射中的键使用用户定义的类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我们可以为 STL 映射中的键使用用户定义的类吗?


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01