std::hash (std::string, std::wstring, std::u16string, std::u32string, std::u8string, std::pmr::string, std::pmr::wstring, std::pmr::u16string, std::pmr::u32string, std::pmr::u8string)

From cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
Member functions
Element access
Iterators
Capacity
Operations
Search
Constants
Deduction guides (C++17)
Non-member functions
I/O
Comparison
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
Numeric conversion
(C++11)(C++11)(C++11)
(C++11)(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
Helper classes
hash<std::string>hash<std::wstring>hash<std::u32string>hash<std::u16string>hash<std::u8string>
(C++11)  (C++11)(C++11)(C++11)(C++20)
hash<std::pmr::string>hash<std::pmr::wstring>hash<std::pmr::u32string>hash<std::pmr::u16string>hash<std::pmr::u8string>
(C++17)(C++17)(C++17)(C++17)(C++20)
 
Defined in header <string>
template<> struct hash<std::string>;

template<> struct hash<std::wstring>;
template<> struct hash<std::u16string>;

template<> struct hash<std::u32string>;
(since C++11)
template<> struct hash<std::pmr::string>;

template<> struct hash<std::pmr::wstring>;
template<> struct hash<std::pmr::u16string>;

template<> struct hash<std::pmr::u32string>;
(since C++17)
template<> struct hash<std::u8string>;
template<> struct hash<std::pmr::u8string>;
(since C++20)

The template specializations of std::hash for the various string classes allow users to obtain hashes of strings.

These hashes equal the hashes of corresponding std::basic_string_view classes: If S is one of these string types, SV is the corresponding string view type, and s is an object of type S, then std::hash<S>()(s) == std::hash<SV>()(SV(s)).

(since C++17)

Example

The following code shows one possible output of a hash function used on a string:

#include <iostream>
#include <string>
#include <string_view>
#include <functional>
#include <memory_resource>
using namespace std::literals;
 
int main()
{
    auto sv = "Stand back! I've got jimmies!"sv;
    std::string s(sv);
    std::pmr::string pmrs(sv); // use default allocator
 
    std::cout << std::hash<std::string_view>{}(sv) << '\n';
    std::cout << std::hash<std::string>{}(s) << '\n';
    std::cout << std::hash<std::pmr::string>{}(pmrs) << '\n';
}

Possible output:

3544599705012401047
3544599705012401047
3544599705012401047

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 2978 C++17 hash support for std::pmr::string and its friends were not enabled enabled

See also

(C++11)
hash function object
(class template)
hash support for string views
(class template specialization)