switch
typedef std::uint64_t hash_t;
constexpr hash_t prime = 0x100000001B3ull;
constexpr hash_t basis = 0xCBF29CE484222325ull;
hash_t hash_(char const* str)
{
hash_t ret{ basis };
while (*str) {
ret ^= *str;
ret *= prime;
str++;
}
return ret;
}
constexpr hash_t hash_compile_time(char const* str, hash_t last_value = basis)
{
return *str ? hash_compile_time(str + 1, (*str ^ last_value) * prime) : last_value;
}
constexpr unsigned long long operator "" _hash(char const* p, size_t)
{
return hash_compile_time(p);
}
//--------------------------usage--------------------------//
//oid simple_switch(char const* str)
//{
// using namespace std;
// switch (hash_(str)) {
// case "first"_hash:
// cout << "1st one" << endl;
// break;
// case "second"_hash:
// cout << "2nd one" << endl;
// break;
// case "third"_hash:
// cout << "3rd one" << endl;
// break;
// default:
// cout << "Default..." << endl;
// }
//}
//--------------------------usage--------------------------//
本文详细介绍了一种基于C++的字符串Hash算法实现,通过使用typedef定义hash_t类型为std::uint64_t,以及利用constexpr关键字定义常量prime和basis,实现了hash_和hash_compile_time两个函数来生成字符串的Hash值。此外,还展示了如何在switch语句中使用自定义的Hash值进行字符串比较,提供了一个简单而高效的字符串匹配解决方案。
7513

被折叠的 条评论
为什么被折叠?



