gpt4 book ai didi

c++ - std::hash 的仿函数

转载 作者:行者123 更新时间:2023-11-30 01:49:30 25 4
gpt4 key购买 nike

考虑到用作键的 ptime 的值主要在小时和日期上有所不同(分钟和秒通常为 0),我想知道计算哈希的最佳方法是什么).

我已经这样做了,但我觉得它很丑而且很慢:

namespace std
{
/**
* Specialize std::hash for ptime
*/
template<>
class hash<boost::posix_time::ptime>
{
public:
size_t operator()(const boost::posix_time::ptime& t) const
{
const auto dt = t.date();
const auto ho = t.time_of_day().hours();
return hash<int>()(dt.day_number()) ^ hash<int>()(ho);
}
};
}

最佳答案

您应该查看的关键字是“avalanche effect”和“哈希组合”。

你可能不应该自己设计散列函数,因为这个领域已经被彻底研究过了。选择雪崩效果好的函数即可,例如MurmurHash .

由于您已经在使用 boost,因此 boost::hash_combine可能是对您来说最合适和有用的解决方案 ( also mentioned here ):

friend std::size_t hash_value(point const& p)
{
std::size_t seed = 0;
boost::hash_combine(seed, p.x);
boost::hash_combine(seed, p.y);
return seed;
}

更重要的是,您可以使用 total_nanoseconds() 之类的东西,而不是使用 day_number 和小时您将实际时间戳转换为天/小时。

关于c++ - std::hash<boost::posix_time::ptime> 的仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29025563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com