boost::shared_ptr的内容作为set的键

Contents of boost::shared_ptr as key for set?

本文关键字:的键 set shared ptr boost      更新时间:2023-10-16

我想在std::unordered_set中存储一系列指针。我希望哈希函数不是基于内存地址,而是基于指针引用的实际对象中包含的一些值。

。(using stdboost命名空间的可读性)

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以获得键。

我的另一个问题是== operator已经为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;

注意两个函子(哈希和相等)必须写成类;自由函数不起作用。(容器保留了一个函数子的私有实例。)这有点烦人,但由于您只会这样做一次,所以应该没有那么糟糕。

通常我建议对std::hashstd::equals进行专门化,但对于像共享指针这样通用的东西,我不太愿意这样做,因为它可能很容易使那些不希望进行专门化的人感到困惑。