我正在使用外部网络库,它返回一些表示打开的套接字的神奇结构,文档说当将它们插入 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/