google dense_hash_map 使用方法

代码
 1 #include <iostream>
 2 #include <google/dense_hash_map>
 3 using std::cout;
 4 using std::endl;
 5 using std::cin;
 6 
 7 int main()
 8 {
 9     //key的类型,value的类型
10     google::dense_hash_map<intint> dMap;
11     // Deletion and empty routines
12     // THESE ARE NON-STANDARD!  I make you specify an                   "impossible" key
13     // value to identify deleted and empty buckets.  You can change the
14     // deleted key as time goes on, or get rid of it entirely to be insert-only.
15     // YOU MUST CALL void set_empty_key(const key_type& key)      
16     //必须设置empty key,否则断言失败
17     //assertion failed !use_empty ...
18     dMap.set_empty_key(-1);
19     typedef google::dense_hash_map<intint>::iterator IntIterator;
20     typedef std::pair<intint> PairInt; 
21 
22     const int SIZE = 1000;
23 
24     //insert
25     cout << "insert lot of number" << endl;
26     for(int i = 0; i<SIZE; ++i)
27     {
28         dMap[i] = -i; //返回value的引用,在赋-i
29     }
30 
31     //find
32     //iterator find(const key_type& key)
33     //const_iterator find(const key_type& key)
34     IntIterator ite = dMap.find(5);
35     cout << "find 5 typed key " << endl
36             << ite->second << endl;    
37 
38     //插入,这种方式,如果key已经存在了,就会不插入了。
39     //pair<iterator, bool> insert(const value_type& obj)
40     //std::pair<const Key,T> 
41     PairInt pairInt(SIZE-5-SIZE-5);
42     std::pair<IntIterator, bool> pairInserted = dMap.insert(pairInt);
43     cout << "insert pair(int, int)" << endl;
44     if(pairInserted.second)
45     {
46         cout << "Key ="<<pairInserted.first->first 
47             << ", Value" << pairInserted.second<<endl;
48     }
49     else
50     {
51             cout << "insert failed" << endl;
52     }
53 
54     //没有找到
55     IntIterator itFind = dMap.find(SIZE+10);
56     if(itFind != dMap.end())
57     {
58         cout << "exist key" << SIZE+10 << endl;
59     }
60     else
61     {
62         cout << "does't exist key" << SIZE+10 << endl;
63     }
64     
65     //这种插入方式的特点:
66     //如果在dMaP存在这个key,就返回这个key的value的引用
67     //如果不存在则向dMap插入这个key,还返回引用
68     int & value = dMap[SIZE-10= -926;
69     if(value)
70     {
71         cout << "inserted success" << endl;
72     }
73     else
74     {
75         cout << "inserted failed" << endl;
76     }
77 
78     std::cin.get();  
79     return 0;
80 }
81 


posted @ 2010-07-21 16:42  thinkpore  阅读(7285)  评论(1编辑  收藏  举报