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 */

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM