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

Bil*_*son 2 c++ boost set

我想存储一系列指针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;
Run Code Online (Sandbox Code Playgroud)

我并不担心结合实际的哈希值(在这里找到答案:http://www.boost.org/doc/libs/1_47_0/doc/html/hash/combine.html),而是取消引用shared_ptr以获取键.

我所关注的另一个问题== operator是已经确定了boost::shared_ptr,我想知道这是否会导致我的方法出现问题?我需要测试对象的相等性,而不是指针.

在集合中存储指针,因为代码的其他几个部分通过自己的指针引用对象.也欢迎任何替代方法.

谢谢

Ker*_* SB 5

有什么问题?定义一个哈希函数和相等,然后你去:

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;
Run Code Online (Sandbox Code Playgroud)

请注意,两个仿函数(哈希和相等)必须写为类; 免费功能不起作用.(容器保留了仿函数的私有实例.)这有点烦人,但是因为你只会这样做一次,所以不应该那么糟糕.

一般情况下我建议专业std::hashstd::equals,但我会毫不犹豫地这样做的东西所以一般作为一个共享指针,因为它可能很容易混淆其他人谁不希望这些专业.