【发布时间】:2015-11-16 11:24:49
【问题描述】:
下面的代码snippet可以对字符串对象做哈希值。我想获得一个二进制字符串(指针和长度)的哈希值。我知道我可以用指针和长度形成一个字符串对象,但是仅仅为此形成一个字符串会有额外的开销。想知道是否可以使用带有两个参数的 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';
}
【问题讨论】:
-
将 std::hash 专门用于包含指针和长度的自定义类?
-
感谢@RichardHodges 的评论,您最终需要调用
std::hash<string>()来获取哈希值吗? -
@codingFun - 您可能想查看 this answer to another question 以了解通过不构造短
std::string节省了多少时间 - 大约 1 ns。