C++11 unordered_set & unordered_map 存储结构体,struct

C++11引入了很多新特性,比如auto ,比如 for(type v : container)等。

数据结构方面最抢眼的应该是引入了unordered_set和unordered_map。比起普通的set 和 map,其内部不再是红黑树排关键字了,而是用的哈系表;来提高查找效率。

不过对于结构体的存储和映射,却没怎么发现别人讲,刚看了篇文章学会了=_=:http://choorucode.com/2012/06/26/c-using-unordered_set/

Mark一下,贴下自己的代码,也方便别人查使用方法。

g++ 编译时注意添加: -std=c++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 */