|
| 1 | +--- |
| 2 | +title: std::hash |
| 3 | +cppdoc: |
| 4 | + revision: |
| 5 | + since: C++11 |
| 6 | +--- |
| 7 | + |
| 8 | +import { CppHeader } from "@components/header"; |
| 9 | +import { Decl, DeclDoc } from "@components/decl-doc"; |
| 10 | +import { Desc, DescList } from "@components/desc-list"; |
| 11 | +import Missing from "@components/Missing.astro"; |
| 12 | +import { ParamDoc, ParamDocList } from "@components/param-doc"; |
| 13 | +import { Revision, RevisionBlock } from "@components/revision"; |
| 14 | + |
| 15 | +Defined in header <CppHeader name="bitset" />. |
| 16 | + |
| 17 | +Defined in header <CppHeader name="coroutine" />. |
| 18 | + |
| 19 | +Defined in header <CppHeader name="chrono" />. |
| 20 | + |
| 21 | +Defined in header <CppHeader name="filesystem" />. |
| 22 | + |
| 23 | +Defined in header <CppHeader name="functional" />. |
| 24 | + |
| 25 | +Defined in header <CppHeader name="memory" />. |
| 26 | + |
| 27 | +Defined in header <CppHeader name="optional" />. |
| 28 | + |
| 29 | +Defined in header <CppHeader name="stacktrace" />. |
| 30 | + |
| 31 | +Defined in header <CppHeader name="string" />. |
| 32 | + |
| 33 | +Defined in header <CppHeader name="string_view" />. |
| 34 | + |
| 35 | +Defined in header <CppHeader name="system_error" />. |
| 36 | + |
| 37 | +Defined in header <CppHeader name="text_encoding" />. |
| 38 | + |
| 39 | +Defined in header <CppHeader name="thread" />. |
| 40 | + |
| 41 | +Defined in header <CppHeader name="typeindex" />. |
| 42 | + |
| 43 | +Defined in header <CppHeader name="variant" />. |
| 44 | + |
| 45 | +Defined in header <CppHeader name="vector" />. |
| 46 | + |
| 47 | +<DeclDoc> |
| 48 | + <Decl slot="decl"> |
| 49 | + <RevisionBlock since="C++11" noborder> |
| 50 | + ```cpp |
| 51 | + template< class Key > |
| 52 | + struct hash; |
| 53 | + ``` |
| 54 | + </RevisionBlock> |
| 55 | + </Decl> |
| 56 | + |
| 57 | + The unordered associative containers `std::unordered_set`, `std::unordered_multiset`, `std::unordered_map`, `std::unordered_multimap` use specializations of the template std::hash as the default hash function. |
| 58 | +</DeclDoc> |
| 59 | + |
| 60 | +Given a type `Key`, each specialization `std::hash<Key>` is either _enabled_ or _disabled_ : |
| 61 | + |
| 62 | +- If `std::hash<Key>` is not provided by the program or the user, it is disabled. |
| 63 | +- Otherwise, `std::hash<Key>` is enabled if all following conditions are satisfied: |
| 64 | + - All following requirements are satisfied: |
| 65 | + - [Hash](../named_req/Hash.html "cpp/named req/Hash") (with `Key` as the function call argument type) |
| 66 | + - [DefaultConstructible](../named_req/DefaultConstructible.html "cpp/named req/DefaultConstructible") |
| 67 | + - [CopyAssignable](../named_req/CopyAssignable.html "cpp/named req/CopyAssignable") |
| 68 | + - [Swappable](../named_req/Swappable.html "cpp/named req/Swappable") |
| 69 | + |
| 70 | + - Given the following values: |
| 71 | + - h, an object of type `std::hash<Key>`. |
| 72 | + - k1 and k2, objects of type `Key`. |
| 73 | + All following requirements are satisfied: |
| 74 | + - If k1 \== k2 is true, h(k1) \== h(k2) is also true. |
| 75 | + - Unless `std::hash<Key>` is a [program-defined specialization](../language/type-id.html#Program-defined_type "cpp/language/type"), h(k1) will never throw an exception. |
| 76 | + |
| 77 | +- Otherwise, `std::hash<Key>` is disabled. |
| 78 | + |
| 79 | +Disabled specializations do not satisfy [Hash](../named_req/Hash.html "cpp/named req/Hash"), do not satisfy [FunctionObject](../named_req/FunctionObject.html "cpp/named req/FunctionObject"), and following values are all false: |
| 80 | + |
| 81 | +- `std::is_default_constructible<std::hash<Key>>::value` |
| 82 | +- `std::is_copy_constructible<std::hash<Key>>::value` |
| 83 | +- `std::is_move_constructible<std::hash<Key>>::value` |
| 84 | +- `std::is_copy_assignable<std::hash<Key>>::value` |
| 85 | +- `std::is_move_assignable<std::hash<Key>>::value` |
| 86 | + |
| 87 | +In other words, they exist, but cannot be used. |
| 88 | +<DeclDoc> |
| 89 | + <Decl slot="decl"> |
| 90 | + <RevisionBlock until="C++20" noborder> |
| 91 | + Nested types: |
| 92 | + |Name|Definition| |
| 93 | + |---|---| |
| 94 | + |`argument_type` (deprecared in C++ 17)| Key| |
| 95 | + |`result_type` (deprecared in C++ 17)| size_t| |
| 96 | + </RevisionBlock> |
| 97 | + </Decl> |
| 98 | +</DeclDoc> |
| 99 | + |
| 100 | +### Member functions |
| 101 | +| | | |
| 102 | +|---|---| |
| 103 | +|`constuctor` | constructs a hash function object <br/> (public member function)| |
| 104 | +|`operator()` | calculates the hash of the argument <br/> (public member function)| |
| 105 | + |
| 106 | + |
| 107 | +### Standard library specializations |
| 108 | +Each header that declares the template std::hash also provides enabled specializations of std::hash for the following types: |
| 109 | + |
| 110 | +- all cv-unqualified arithmetic types |
| 111 | +- all cv-unqualified enumeration types |
| 112 | +- all cv-unqualified pointer types |
| 113 | +- std::nullptr_t |
| 114 | + |
| 115 | +On top of that, some headers also provide other enabled std::hash specializations for library types (see below). |
| 116 | + |
| 117 | + |
| 118 | + |
| 119 | +<DeclDoc> |
| 120 | + <Decl slot="decl"> |
| 121 | + <RevisionBlock since="C++17" noborder> |
| 122 | + For all std::hash specializations provided by the standard library except the following, all their member functions are noexcept: |
| 123 | + - `std::hash<std::optional>` |
| 124 | + - `std::hash<std::variant>` |
| 125 | + - `std::hash<std::unique_ptr>` |
| 126 | + |
| 127 | + <RevisionBlock since="c++26"> |
| 128 | + - `std::hash<std::chrono::duration>` |
| 129 | + - `std::hash<std::chrono::time_point>` |
| 130 | + - `std::hash<std::chrono::zoned_time>` |
| 131 | + </RevisionBlock> |
| 132 | + </RevisionBlock> |
| 133 | + </Decl> |
| 134 | +</DeclDoc> |
| 135 | + |
| 136 | + |
| 137 | +## Notes |
| 138 | + |
| 139 | +The actual hash functions are implementation-dependent and are not required to fulfill any other quality criteria except those specified above. Notably, some implementations use trivial (identity) hash functions which map an integer to itself. In other words, these hash functions are designed to work with unordered associative containers, but not as cryptographic hashes, for example. |
| 140 | + |
| 141 | +Hash functions are only required to produce the same result for the same input within a single execution of a program; this allows salted hashes that prevent collision denial-of-service attacks. |
| 142 | + |
| 143 | +There is no specialization for C strings. `std::hash<const char*>` produces a hash of the value of the pointer (the memory address), it does not examine the contents of any character array. |
| 144 | + |
| 145 | +Additional specializations for `std::pair` and the standard container types, as well as utility functions to compose hashes are available in `boost::hash`. |
| 146 | + |
| 147 | + |
| 148 | +## Example |
| 149 | + |
| 150 | +```cpp |
| 151 | +#include <cstddef> |
| 152 | +#include <functional> |
| 153 | +#include <iomanip> |
| 154 | +#include <iostream> |
| 155 | +#include <string> |
| 156 | +#include <unordered_set> |
| 157 | + |
| 158 | +struct S |
| 159 | +{ |
| 160 | + std::string first_name; |
| 161 | + std::string last_name; |
| 162 | + bool operator==(const S&) const = default; // since C++20 |
| 163 | +}; |
| 164 | + |
| 165 | +// Before C++20. |
| 166 | +// bool operator==(const S& lhs, const S& rhs) |
| 167 | +// { |
| 168 | +// return lhs.first_name == rhs.first_name && lhs.last_name == rhs.last_name; |
| 169 | +// } |
| 170 | + |
| 171 | +// Custom hash can be a standalone function object. |
| 172 | +struct MyHash |
| 173 | +{ |
| 174 | + std::size_t operator()(const S& s) const noexcept |
| 175 | + { |
| 176 | + std::size_t h1 = std::hash<std::string>{}(s.first_name); |
| 177 | + std::size_t h2 = std::hash<std::string>{}(s.last_name); |
| 178 | + return h1 ^ (h2 << 1); // or use boost::hash_combine |
| 179 | + } |
| 180 | +}; |
| 181 | + |
| 182 | +// Custom specialization of std::hash can be injected in namespace std. |
| 183 | +template<> |
| 184 | +struct std::hash<S> |
| 185 | +{ |
| 186 | + std::size_t operator()(const S& s) const noexcept |
| 187 | + { |
| 188 | + std::size_t h1 = std::hash<std::string>{}(s.first_name); |
| 189 | + std::size_t h2 = std::hash<std::string>{}(s.last_name); |
| 190 | + return h1 ^ (h2 << 1); // or use boost::hash_combine |
| 191 | + } |
| 192 | +}; |
| 193 | + |
| 194 | +int main() |
| 195 | +{ |
| 196 | + std::string str = "Meet the new boss..."; |
| 197 | + std::size_t str_hash = std::hash<std::string>{}(str); |
| 198 | + std::cout << "hash(" << std::quoted(str) << ") =\t" << str_hash << '\n'; |
| 199 | + |
| 200 | + S obj = {"Hubert", "Farnsworth"}; |
| 201 | + // Using the standalone function object. |
| 202 | + std::cout << "hash(" << std::quoted(obj.first_name) << ", " |
| 203 | + << std::quoted(obj.last_name) << ") =\t" |
| 204 | + << MyHash{}(obj) << " (using MyHash) or\n\t\t\t\t" |
| 205 | + << std::hash<S>{}(obj) << " (using injected specialization)\n"; |
| 206 | + |
| 207 | + // Custom hash makes it possible to use custom types in unordered containers. |
| 208 | + // The example will use the injected std::hash<S> specialization above, |
| 209 | + // to use MyHash instead, pass it as a second template argument. |
| 210 | + std::unordered_set<S> names = {obj, {"Bender", "Rodriguez"}, {"Turanga", "Leela"}}; |
| 211 | + for (auto const& s: names) |
| 212 | + std::cout << std::quoted(s.first_name) << ' ' |
| 213 | + << std::quoted(s.last_name) << '\n'; |
| 214 | +} |
| 215 | +``` |
| 216 | + |
| 217 | +Possible outputs: |
| 218 | + |
| 219 | +```cpp |
| 220 | +hash("Meet the new boss...") = 10656026664466977650 |
| 221 | +hash("Hubert", "Farnsworth") = 12922914235676820612 (using MyHash) or |
| 222 | + 12922914235676820612 (using injected specialization) |
| 223 | +"Bender" "Rodriguez" |
| 224 | +"Turanga" "Leela" |
| 225 | +"Hubert" "Farnsworth" |
| 226 | +``` |
| 227 | + |
| 228 | +```cpp |
| 229 | +// Simple move constructor |
| 230 | +// the expression "arg.member" is lvalue |
| 231 | +A(A&& arg) : member(std::move(arg.member)) {} |
| 232 | + |
| 233 | +// Simple move assignment operator |
| 234 | +A& operator=(A&& other) { |
| 235 | + member = std::move(other.member); |
| 236 | + return *this; |
| 237 | +} |
| 238 | +``` |
| 239 | + |
| 240 | +## Defect reports |
| 241 | + |
| 242 | +The following behavior-changing defect reports were applied retroactively to previously published C++ standards. |
| 243 | + |
| 244 | +| DR | Applied to | Behavior as published | Correct behavior | |
| 245 | +| --- | --- | --- | --- | |
| 246 | +| [LWG 2119](https://cplusplus.github.io/LWG/issue2119) | C++11 | specializations for extended integer types were missing | provided | |
| 247 | +| [LWG 2148](https://cplusplus.github.io/LWG/issue2148) | C++11 | specializations for enumerations were missing | provided | |
| 248 | +| [LWG 2543](https://cplusplus.github.io/LWG/issue2543) | C++11 | `std::hash` might not be SFINAE-friendly | made SFINAE-friendly | |
| 249 | +| [LWG 2817](https://cplusplus.github.io/LWG/issue2817) | C++11 | specialization for [std::nullptr\_t](../types/nullptr_t.html "cpp/types/nullptr_t") was missing | provided | |
| 250 | + |
0 commit comments