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 中的键
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
