C ++标准库哈希码示例

时间:2015-06-15 05:47:10

标签: c++ hash stl hashmap

我解决了在列表中找到重复项的问题

我使用了一个集合的属性,它只包含唯一成员

set<int> s;

// insert the new item into the set
s.insert(nums[index]);

// if size does not increase there is a duplicate
if (s.size() == previousSize)
{
   DuplicateFlag = true;
   break;
}

现在我正在尝试使用标准库中的哈希函数解决相同的问题。我有这样的示例代码

#include <functional>

using namespace __gnu_cxx;
using namespace std;

hash<int> hash_fn2;
int x = 34567672;
size_t int_hash2 = hash_fn2(x);

cout << x << "   " << int_hash2 << '\n';

x和int_hash2总是一样的 我在这里错过了什么吗?

2 个答案:

答案 0 :(得分:2)

对于std::hash<int>,可以直接返回原始int值。从specification开始,只需要确保两个不同的参数k1k2不相等,std::hash<Key>()(k1) == std::hash<Key>()(k2)应该非常小,接近{{}的概率1}}。清楚地返回原始值满足1.0/std::numeric_limits<size_t>::max()

的要求

答案 1 :(得分:0)

  

x和int_hash2总是一样我在这里错过了什么?

是。你说“我正在尝试用哈希函数来解决同样的问题”,但哈希函数不是std::set<>的替代功能,并且不能 - 本身 - 不能用来解决你的问题poroblem。您可能希望使用std::unordered_set<>,它将在内部使用哈希表,使用std::hash<>函数(默认情况下)帮助它从元素映射到“桶”。出于哈希表的目的,返回输入的整数的哈希函数通常足够好,如果程序员不希望将其首选备选方案作为模板参数提供。

无论如何,要尝试哈希表方法,只需在原始代码中将std:set<int> s;更改为std::unordered_set<int> s;