Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
johnwongx opened this issue Apr 24, 2025 · 1 comment
Open

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

johnwongx opened this issue Apr 24, 2025 · 1 comment
Assignees
Labels
bug Something isn't working

Comments

@johnwongx
Copy link

johnwongx commented Apr 24, 2025

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的内容来散列的吗?这么设计是有什么考虑吗?

@mutouyun
Copy link
Owner

有道理,这里确实有问题,误把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 mutouyun added the bug Something isn't working label Apr 24, 2025
@mutouyun mutouyun self-assigned this Apr 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants