C++中设置无序,为什么需要哈希
Unordered set in C++, why is hash needed?
我只想在一个无序集合中存储几个对象。创建几组,
auto set1 = std::unordered_set<Myclass>();
我有时会收到这样的错误,很多:
未定义模板"std::__1::哈希"的隐式实例化
除了开箱即用的unordered_set之外,没有其他选择吗?为什么需要"哈希"?
std::unordered_set
通过对您使用的键进行哈希处理来索引其存储中的值,这与哈希表或C++ std::unordered_map
实现非常相似。
如果您不想为 Myclass
编写哈希函数,只需改用 std::set
即可。这可能比定义哈希函数并使用std::unordered_set
的性能更差,但如果编写哈希函数对您的类来说很困难,则可能是值得的。取决于类和应用程序。
如果要使用std::unordered_set
,则需要为Myclass
提供一个哈希函数。要么为您的类提供std::hash
专用化,要么提供哈希策略以std::unordered_set
.
//specialize std::hash
namespace std
{
template<>
struct hash<Myclass>
{
typedef Myclass argument_type;
typedef std::size_t result_type;
result_type operator()(argument_type const& s) const
{
//some code to hash a Myclass object
}
};
}
auto set1 = std::unordered_set<Myclass>();
//hashing policy version
class MyclassHash
{
public:
std::size_t operator()(Myclass const& s) const
{
//some code to hash a Myclass object
}
};
auto set1 = std::unordered_set<Myclass, MyclassHash>();
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 使用Qt C++计算类似Git的SHA1哈希
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么C++ STL 哈希表 (unordered_map) 不接受向量作为键
- 为什么我们没有用于地图的哈希和捕食函子?
- 为什么C++哈希函数的返回类型是 std::size_t,而不是独立于平台的类型?
- 为什么哈希<常量字符*>适用于字符串而不是字符串变量?
- 实现将字符串映射到 C++ 中的数组的哈希表。我一直在"Debug Assertion Failed",我不知道为什么
- C++中设置无序,为什么需要哈希
- 为什么我的空间哈希这么慢
- 将链接哈希表初始化为 NULL。获取"lvalue required as left operand of assignment"错误。为什么?这是我的代码:
- 为什么不同程序执行之间的哈希值不一致
- 为什么我在为矢量实现这个简单的哈希时出现错误<int>?
- 为什么python的字典是作为哈希表实现的,而std::map是基于树的?
- 为什么在最坏的情况下unorder_set重哈希复杂度可能是O(n^2)
- 为什么c++标准库不包含哈希表实现
- 为什么哈希函数返回size_t,以及如何使用它
- 为什么std::map是红黑树而不是哈希表
- 为什么这个哈希表函数显示编译错误