boost::shared_ptr的内容作为set的键
Contents of boost::shared_ptr as key for set?
我想在std::unordered_set
中存储一系列指针。我希望哈希函数不是基于内存地址,而是基于指针引用的实际对象中包含的一些值。
。(using std
和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
以获得键。
我的另一个问题是== 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::hash
和std::equals
进行专门化,但对于像共享指针这样通用的东西,我不太愿意这样做,因为它可能很容易使那些不希望进行专门化的人感到困惑。
相关文章:
- 使用一个考虑到std::map中键值的滚动或换行的键
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 使用字符数组作为 Map 中的键
- 如何在C++中访问有序映射中的键的范围/间隔?
- 查找不存在的键时,unordered_map返回什么
- 如何使用 std::string 作为 QHash 的键?
- 是否有像地图这样的C++结构,但我得到的不是值的键,而是值的句柄?
- C++ 映射的键/值的用户自定义名称?
- 重构使用动态强制转换的 std::set 的比较运算符
- 比较它们之间的元素并获取公共值的键
- 插入 std::set 作为 std::map 的键
- 在std :: Map或std :: set中找到具有给定前缀的键的优雅方法
- set 如何与唯一键一起工作,但在C++中具有等效的键值
- 为什么要使用std ::少用作默认函数来比较std :: map and std :: set中的键
- 模板化的使用是否为具有自定义键的unordered_map/set创建了一个良好的模式
- 查找 std::set 中的键成对存储
- set::find()找不到集合中的键
- boost::shared_ptr的内容作为set的键
- Std::vector作为Std::set和Std::unordered_set中的键
- 在 std::set 或 std::map 的键中使用weak_ptr是否安全