我想在 std::unordered_set
中存储一系列指针。我希望哈希函数不基于内存地址,而是基于指针引用的实际对象中包含的某些值。
例如(使用 std
和 boost
命名空间以 boost 可读性)
class MyClass {
...
//some values I want to use as the key for the hash
double a;
int b;
int c;
}
typedef shared_ptr<MyClass> MyClassPtr;
set<MyClassPtr> mySet;
我并不担心组合实际的哈希值(在这里找到答案:http://www.boost.org/doc/libs/1_47_0/doc/html/hash/combine.html),而是取消引用shared_ptr
来获取 key 。
我担心的另一个问题是 == 运算符
已经为 boost::shared_ptr
定义了,我想知道这是否会导致我的方法出现问题?我需要测试对象的相等性,而不是指针。
将指针存储在集合中,因为代码的其他几个部分通过它们自己的指针引用对象。也欢迎任何替代方法。
谢谢
最佳答案
有什么问题吗?定义一个哈希函数和等式,然后就可以了:
struct MyClassHash
{
inline std::size_t operator()(const MyClassPtr & p)
{
return 4; // prone to hash collisions, improve on this
}
};
struct MyClassEqual
{
inline bool operator()(const MyClassPtr & p, const MyClassPtr & q)
{
return false; // implement
}
};
typedef std::unordered_set<MyClassPtr, MyClassHash, MyClassEqual> MySet;
请注意,两个仿函数(散列和相等)必须编写为类;免费功能不起作用。 (容器保留了仿函数的私有(private)实例。)这有点烦人,但由于您只会这样做一次,所以应该不会那么糟糕。
通常我建议专门化 std::hash
和 std::equals
,但我会犹豫是否要使用像共享指针这样通用的东西,因为它可能很容易让其他不期望这些特化的人感到困惑。
关于c++ - boost::shared_ptr 的内容作为 set 的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8070243/