C++11 unordered_set with std::owner_less-like hashing

标签 c++ c++11 stl shared-ptr unordered-map

我正在使用外部网络库,它返回一些表示打开的套接字的神奇结构,文档说当将它们插入 STL 容器时,应该使用 std::owner_less 比较它们。

std::map<MagicStructure, std::shared_ptr<Client>, std::owner_less<MagicStructure>> sockets;

但是我想改用unordered_map。我该怎么做? std::owner_less 是一个比较器,它对 HashMap 毫无用处。挖掘源代码,MagicStructure 似乎是 std::shared_ptr 的类型定义。

最佳答案

不幸的是,您似乎必须使用map,而对于这种情况不能使用unordered_map:http://wg21.cmeerw.net/lwg/issue1406

Hash support for the ownership-based equivalence relation cannot be provided by any user-defined manner because information about ownership sharing is not available to users at all. Therefore, the only way to provide ownership-based hash support is to offer it intrusively by the standard library.

换句话说,在 shared_ptr 中有存储(由 get() 返回)和拥有的指针(当引用计数达到 0 时删除):http://www.cplusplus.com/reference/memory/shared_ptr/get/ .要在 unordered_map 中使用自有指针,您需要基于自有指针的 hash()equals() 操作。但它们在STL 中没有提供。而且你不能自己实现它们(不重新实现 shared_ptr 并更改你的 MagicStructure 的定义)因为拥有的指针没有被 shared_ptr 暴露.

关于C++11 unordered_set with std::owner_less-like hashing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31378130/

相关文章:

c++ - 如何在 C++ 中为 PEGTL 通过属性/标识符定义 unicode 范围

c++ - OpenGL 3.3/GLSL 和 C++ 错误 : "must write to gl_Position"

c++ - 将 MPI 与 c++11 和 CUDA 相结合

c++ - 如何定义与使用 lambda 兼容的函数指针并将捕获作为回调

c++ - 为什么整数比较比字符串比较快?

c++ - 将整数映射到数组

c++ 如何使用 cin 来输入这样的值?

c++ - std::put_time 格式

c++ - float <-> std::string 转换替代方案?

c++ - 我可以从它包含的数据中分离一个 std::vector<char> 吗?