c++ 自定pair等数据类型的hash以及相等判定来满足unordered_set、unordered_map的需要

第一种:

1 #include <iostream>
 2 #include <unordered_set>
 3 #include <utility>
 4 #include <vector>
 5 
 6 using namespace std;
 7 
 8 using KEY = pair<int,int>;
 9 
10 //    自定义pair的哈希
11 struct PairHash
12 {
13     size_t operator()(const KEY& key) const
14     {
15         return hash<int>{}(key.first) ^ hash<int>{}(key.second);
16     }
17 };
18 
19 //    自定义pair的相等判断
20 bool operator==(const KEY& lhs,const KEY& rhs)
21 {
22     return lhs.first == rhs.first && lhs.second == rhs.second;
23 }
24 
25 int main()
26 {
27     unordered_set<pair<int,int>,PairHash> us;
28     vector<pair<int,int>> v{{1,2},{3,4},{5,6},{1,2},{7,8},{3,7},{3,4} },res;
29     for(auto& p:v)
30     {
31         if(us.contains(p) ) res.emplace_back(p);
32         else us.insert(p);
33     }
34     for(auto& pp:res) cout << pp.first << ' ' << pp.second << endl;
35     return 0;
36 }

第二种:

1 #include <iostream>
 2 #include <unordered_set>
 3 #include <utility>
 4 #include <vector>
 5 
 6 using namespace std;
 7 
 8 using KEY = pair<int,int>;
 9 
10 //    自定义hash
11 struct PairHash
12 {
13     size_t operator()(const KEY& key) const
14     {
15         return hash<int>{}(key.first) ^ hash<int>{}(key.second);
16     }
17 };
18 
19 //    定义相等判断,这里用仿函数
20 struct PairEqualTo
21 {
22     bool operator()(const KEY& p1,const KEY& p2) const noexcept
23     {
24         return p1.first == p2.first && p1.second == p2.second;
25     }
26 };
27 
28 int main()
29 {
30     unordered_set<pair<int,int>,PairHash,PairEqualTo> us;  // 传入hash函数和相等判断的仿函数
31     vector<pair<int,int>> v{{1,2},{3,4},{5,6},{1,2},{7,8},{3,7},{3,4} },res;
32     for(auto& p:v)
33     {
34         if(us.contains(p) ) res.emplace_back(p);
35         else us.insert(p);
36     }
37     for(auto& pp:res) cout << pp.first << ' ' << pp.second << endl;
38     return 0;
39 }

原文链接: https://www.cnblogs.com/limancx/p/13850884.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/204233

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午9:47
下一篇 2023年2月12日 下午9:47

相关推荐