快速访问哈希函数(不使用字符串对象)

时间:2015-08-22 16:52:41

标签: c++ hash

以下代码git page可以对字符串对象执行哈希值。我想得到一个二进制字符串(指针和长度)的哈希值。我知道我可以用指针和长度形成一个字符串对象,但是只有为此形成一个字符串还有额外的开销。不知道是否可以使用带有两个参数的std哈希函数:指针和长度。

感谢。

#include <iostream>
#include <functional>
#include <string>

int main()
{
    std::string str = "Meet the new boss...";
    std::hash<std::string> hash_fn;
    std::size_t str_hash = hash_fn(str);

    std::cout << str_hash << '\n';
}

1 个答案:

答案 0 :(得分:2)

我在堆栈溢出中发现这篇文章,它表明底层的散列函数实际上是字符串内部缓冲区中字节的函数:

What is the default hash function used in C++ std::unordered_map?

但是,不是通过调用标准库中的内部函数来冒险未定义的行为,为什么不问问题,&#34;通过创建std::string&#34;我将失去多少性能?鉴于你总是可以创建一个static const这样的字符串(零开销)我想知道你实际要保存什么?