How to hash std::string?

65,806

Solution 1

For a quick solution involving no external libraries, you can use hash<std::string> to hash strings. It's defined by including the header files hash_map or unordered_map (or some others too).

#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++".

Solution 2

using c++11, you can:

#include <string>
#include <unordered_map>

std::size_t h1 = std::hash<std::string>{}("MyString");
std::size_t h2 = std::hash<double>{}(3.14159);

see more here.

Solution 3

You can use the STL functor hash. See if your STL lib has it or not.

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..

Share:
65,806
Septagram
Author by

Septagram

Updated on February 22, 2021

Comments

  • Septagram
    Septagram about 3 years

    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?