Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <map>
- #include <unordered_map>
- using Pair = std::pair<int, int>;
- struct PairHash {
- size_t operator()(const Pair &a) const {
- return (a.first << 8) + a.second;
- }
- };
- template <>
- struct std::hash<Pair>
- {
- // const关键字是必须的
- size_t operator()(const Pair &t) const
- {
- return t.first + t.second;
- }
- };
- int main()
- {
- bool a1 = Pair{1, 2} < Pair{1, 3}; // true
- bool a2 = Pair{1, 9} < Pair{2, 3}; // true
- bool a3 = Pair{1, 2} == Pair{1, 2}; // true
- std::cout << a1 << ", " << a2 << ", " << a3 << std::endl;
- // 1.std::pair 支持比较大小,因此std::map直接可以使用Pair作为key
- std::map<Pair, std::string> map;
- map.insert({{1, 2}, "AA"});
- // 2.std::pair 不支持hash函数,因此不能直接作为key
- // std::unordered_map<Pair, std::string> hashmap; // error
- // 2.1)define hash function
- // std::unordered_map<Pair, std::string, PairHash> hashmap1;
- // hashmap1.insert({{1, 2}, "BB"});
- // 2.2)specialize template std::hash<T>
- std::unordered_map<Pair, std::string> hashmap2;
- hashmap2.insert({{1, 2}, "BB"});
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement