指针作为键在地图C ++ STL [英] Pointers as keys in map 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!