C++11 unordered_set & unordered_map 存儲結構體(struct)

C++11引入了不少新特性,好比auto ,好比 for(type v : container)等。ios

數據結構方面最搶眼的應該是引入了unordered_set和unordered_map。比起普通的set 和 map,其內部再也不是紅黑樹排關鍵字了,而是用的哈系表;來提升查找效率。c++

不過對於結構體的存儲和映射,卻沒怎麼發現別人講,剛看了篇文章學會了=_=:http://choorucode.com/2012/06/26/c-using-unordered_set/數據結構

Mark一下,貼下本身的代碼,也方便別人查使用方法。spa

g++ 編譯時注意添加: -std=c++11c++11

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <set>
 4 #include <unordered_set>
 5 #include <unordered_map>
 6 using namespace std;
 7 
 8 struct Node {
 9     Node() {}
10     Node(int _x, int _y):x(_x), y(_y) {}
11     int x, y;
12     bool operator == (const Node &t) const {
13         return  x==t.x && y==t.y;
14     }
15 };
16 struct NodeHash {
17     std::size_t operator () (const Node &t) const {
18         return  t.x * 100 + t.y;
19     }
20 };
21 unordered_set <Node, NodeHash> h_set;
22 unordered_map <Node, string, NodeHash> h_map;
23 
24 int main()
25 {
26     h_set.insert(Node(1, 2));
27     int x, y;
28     cin >> x >> y;
29     if(h_set.find(Node(x, y)) == h_set.end()) {
30         cout << "Not found" << endl;
31     }
32     else  cout << "Found succeed" << endl;
33     h_map[Node(1, 2)] = "World";
34     cout << h_map[Node(1, 2)] << endl;
35     return 0;
36 }
37 
38 /*
39 
40 輸入: 1 2
41 
42 輸出:
43 
44 1 2
45 Found succeed
46 World
47 
48 */
相關文章
相關標籤/搜索