Custom Hash Functions
Hash your own types.
Why Custom Hashes?
Unordered containers need a way to hash their keys. Built-in types and std::string already have hashes, but your own types do not. You must provide one.
#include <iostream>
#include <unordered_set>
#include <string>
int main() {
std::unordered_set<std::string> s{"hi"};
std::cout << s.count("hi") << '\n';
return 0;
}The std::hash Template
std::hash is a functor that maps a value to a size_t. You call it like a function.
#include <iostream>
#include <functional>
#include <string>
int main() {
std::hash<std::string> h;
std::cout << "hash exists and returns a size_t\n";
std::size_t v = h("hello");
std::cout << (v != 0 ? "non-zero hash" : "zero") << '\n';
return 0;
}All lessons in this course
- std::unordered_map
- unordered_set
- Custom Hash Functions
- Performance Considerations