Pointers as keys in map C++ STL(指针作为映射 C++ STL 中的键)
问题描述
我有一个问题,当在地图中用作键时,如何处理指向自定义对象的指针.更具体地说,如果我定义
I have a question on how pointers to a custom object are handled when used as Keys in an map. More specifically if I define
std::map< CustomClass*, int > foo;
默认的 C++ 实现可以处理这些指针吗?还是我需要定义一个自定义比较器函数来处理它?一般来说,使用指向对象的指针作为键是一种好习惯吗?
Would the default C++ implementation work to handle these pointers? Or do I need to define a custom comparator function to handle it? In general, is it good practice to use pointers to objects as keys?
推荐答案
默认实现会比较指针存储的地址,因此不同的对象会被视为不同的键.但是,不会考虑对象的逻辑状态.例如,如果您使用 std::string *
作为键,两个不同的 std::string
对象具有相同的 "Hello"
文本> 将被视为不同的键!(当按他们的地址存储在地图中时)
The default implementation will compare the addresses stored by the pointers, so different objects will be considered as different keys. However, the logical state of the object will not be considered. For example, if you use std::string *
as the key, two different std::string
objects with the same text of "Hello"
would be considered a different key! (When stored in the map by their addresses)
只要您理解上述重要区别,就可以使用指针作为键.
It's ok to use pointers as keys so long as you understand the important difference above.
这篇关于指针作为映射 C++ STL 中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:指针作为映射 C++ STL 中的键


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