我正在使用cpp实用程序中的std::散列来生成字符串的散列。我的要求是生成固定大小的11位数字哈希。哈希函数不必很大,就不会有冲突。我唯一的要求是生成固定大小的11位哈希。任何输入都会很好,我也可以使用一些自定义的散列函数。
#include <iostream>
#include <string>
#include <functional>
#include <iomanip>
#include <unordered_set>
int main()
{
std::hash<std::string> hash_fn;
std::string s1 = "Stand back! I've got jimmies!";
size_t hash1 = hash_fn(s1);
std::cout << hash1 << '\n'; // OUTPUT: 3544599705012401047
s1 = "h";
hash1 = hash_fn(s1);
std::cout << hash1 << '\n'; // OUTPUT: 11539147918811572172
return 1;
}发布于 2018-02-28 10:07:54
这很简单,您可以简单地将结果模块化:
size_t fix_11digits(size_t n) { return n % 100000000000LU; }用法:
size_t hash1 = fix_11digits(hash_fn(s1));编辑:
如果要获取哈希的实际字符串,请注意前导零:
std::ostringstream ss;
ss << std::setw(11) << std::setfill('0') << hash1;
std::string s{ss.str()};https://stackoverflow.com/questions/49026756
复制相似问题