指针作为映射 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.
相关文章