C++ 如何散列 std::string?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8029121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to hash std::string?
提问by Septagram
I'm making a little utility to help me remember passwords by repetition. I'd like to enter password to be remembered only once every day and not before each session. Of course, I wouldn't store a password itself, but would gladly store its hash.
我正在制作一个小实用程序来帮助我通过重复记住密码。我想每天输入一次要记住的密码,而不是在每次会话之前。当然,我不会自己存储密码,但会很乐意存储它的哈希值。
So, what are the easiest ways to get a hash from std::string
using the C++ Standard Library?
那么,std::string
使用 C++ 标准库获取散列的最简单方法是什么?
回答by Seth Carnegie
For a quick solution involving no external libraries, you can use hash<std::string>
to hash string
s. It's defined by including the header files hash_map
or unordered_map
(or some others too).
对于不涉及外部库的快速解决方案,您可以使用hash<std::string>
散列string
s。它是通过包含头文件hash_map
或unordered_map
(或其他一些)来定义的。
#include <string>
#include <unordered_map>
hash<string> hasher;
string s = "heyho";
size_t hash = hasher(s);
If you decide you want the added security of SHA, you don't have to download the large Crypto++ library if you don't need all its other features; there are plenty of standalone implementations on the internet, just search for "sha implementation c++".
如果您决定需要 SHA 的附加安全性,并且不需要它的所有其他功能,则不必下载大型 Crypto++ 库;互联网上有很多独立的实现,只需搜索“sha implementation c++”。
回答by Ou Wei
回答by Kashyap
You can use the STL functor hash. See if your STL lib has it or not.
您可以使用STL 函子 hash。看看你的 STL 库是否有它。
Note that this one returns a size_t
, so range is numeric_limits<size_t>::min()
numeric_limits<size_t>::max()
. You'll have to use SHA or something if that's not acceptable..
请注意,这个返回 a size_t
,因此范围是numeric_limits<size_t>::min()
numeric_limits<size_t>::max()
。如果这是不可接受的,您将不得不使用 SHA 或其他东西。