| 1 |
#include <string> |
| 2 |
#include <iostream> |
| 3 |
|
| 4 |
#include <unordered_set> |
| 5 |
|
| 6 |
//key |
| 7 |
class Key |
| 8 |
{ |
| 9 |
std::string d_name; |
| 10 |
std::string d_phone; |
| 11 |
|
| 12 |
public: |
| 13 |
Key(std::string const &name, std::string const &phone); |
| 14 |
bool operator==(Key const &other) const = default; |
| 15 |
|
| 16 |
std::string const &name() const; |
| 17 |
std::string const &phone() const; |
| 18 |
}; |
| 19 |
//= |
| 20 |
|
| 21 |
inline std::string const &Key::name() const |
| 22 |
{ |
| 23 |
return d_name; |
| 24 |
} |
| 25 |
|
| 26 |
inline std::string const &Key::phone() const |
| 27 |
{ |
| 28 |
return d_phone; |
| 29 |
} |
| 30 |
|
| 31 |
//KeyHash |
| 32 |
struct KeyHash |
| 33 |
{ |
| 34 |
size_t operator()(Key const &key) const; // noexcept; |
| 35 |
}; |
| 36 |
|
| 37 |
size_t KeyHash::operator()(Key const &key) const // noexcept |
| 38 |
{ |
| 39 |
std::hash<std::string> hashObj; |
| 40 |
|
| 41 |
return hashObj(key.name()) ^ (hashObj(key.phone()) << 1); |
| 42 |
} |
| 43 |
//= |
| 44 |
|
| 45 |
//Hash |
| 46 |
template<> |
| 47 |
struct std::hash<Key> |
| 48 |
{ |
| 49 |
std::size_t operator()(Key const &key) const; // noexcept; |
| 50 |
}; |
| 51 |
|
| 52 |
size_t std::hash<Key>::operator()(Key const &key) const // noexcept |
| 53 |
{ |
| 54 |
std::hash<std::string> hashObj; |
| 55 |
|
| 56 |
return hashObj(key.name()) ^ (hashObj(key.phone()) << 1); |
| 57 |
} |
| 58 |
//= |
| 59 |
|
| 60 |
using namespace std; |
| 61 |
|
| 62 |
Key::Key(string const &name, string const &phone) |
| 63 |
: |
| 64 |
d_name(name), |
| 65 |
d_phone(phone) |
| 66 |
{} |
| 67 |
|
| 68 |
int main() |
| 69 |
{ |
| 70 |
Key k1{ "hello", "world" }; |
| 71 |
Key k2{ "something", "else" }; |
| 72 |
|
| 73 |
cout << (k1 == k1) << ' ' << (k1 == k2) << '\n'; |
| 74 |
|
| 75 |
unordered_set<Key> keySet; |
| 76 |
unordered_set<Key, KeyHash> key2; |
| 77 |
|
| 78 |
keySet.insert(k1); |
| 79 |
keySet.insert(k2); |
| 80 |
|
| 81 |
cout << keySet.find(k1)->name() << '\n'; |
| 82 |
} |