cpp-ipc icon indicating copy to clipboard operation
cpp-ipc copied to clipboard

hash 以string 为key的时候的计算方式

Open zanewong233 opened this issue 7 months ago • 1 comments

template <> struct hash<string> {
    std::size_t operator()(string const &val) const noexcept {
        return std::hash<char const *>{}(val.c_str());
    }
};

这里边自定义的hash对于string为key时用的是字符串的地址值作为散列函数的输入,正常来说不是应该按照string的内容来散列的吗?这么设计是有什么考虑吗?

zanewong233 avatar Apr 24 '25 02:04 zanewong233

有道理,这里确实有问题,误把std::hash<char const *>作为C字符串hash函数了。这里之所以不直接用std::hash<std::string>的原因是内存构造器不一样,会导致字符串产生一次深拷贝;另外为了兼容C++14,std::string_view的特化也不方便直接用。

看来这里需要自己手写一个字符串哈希函数。

https://en.cppreference.com/w/cpp/utility/hash https://stackoverflow.com/questions/34597260/stdhash-value-on-char-value-and-not-on-memory-address https://stackoverflow.com/questions/7666509/hash-function-for-string

mutouyun avatar Apr 24 '25 05:04 mutouyun