hashtable的运用实例

 1 #include <hash_set>
 2 #include <iostream>
 3 using namespace std;
 4 int main()
 5 {
 6     hashtable<int,
 7         int,
 8         hash<int>,
 9         identify<int>,
10         equal_to<int>,
11         alloc> iht(50,hash<int>,equal_to<int>());    //指定保留50个bucket(桶)
12     cout<<iht.size()<<endl;                //0
13     cout<<iht.bucket_count()<<endl;        //53这是STL提供的最小质数
14     cout<<iht.max_bucket_count()<<endl;    //4294967291
15 
16     iht.insert_unique(59);
17     iht.insert_unique(63);
18     iht.insert_unique(108);
19     iht.insert_unique(2);
20     iht.insert_unique(53);
21     iht.insert_unique(55);
22     cout<<iht.size()<<endl;                //6,此即hashtable<T>::num_elements
23 
24     /*一下声明一个hashtable迭代器*/
25     hashtable<int,
26         int,
27         hash<int>,
28         identify<int>,
29         equal_to<int>,
30         alloc>::iterator ite = iht.begin();
31 
32     for(int i = 0;i<iht.size();i++,ite++)
33         cout<< *ite<<<' ';    //输出:53 55 2 108 59 63   并没有顺序
34     cout<<endl;
35 
36     /*遍历所有buckets,如果其节点个数不为0,就打印节点个数,为0不打印*/
37     for(int i = 0;i<iht.bucket_count();i++)
38     {
39         int n = iht.elem_in_bucket(i);
40         if(n!=0)
41             cout<<"bucket["<<i<<"] has"<<n<<" elems."<<endl;
42     }
43     /*
44     输出:
45     bucket[0] has 1 elems.
46     bucket[2] has 3 elems.
47     bucket[6] has 1 elems.
48     bucket[10] has 1 elems.
49     */
50 
51     /*为了验证“bucket(list)”的容量就是buckets vector的大小(这是从
52     hashtable<T>::resize()得知的结果),我刻意将元素加到54个,
53     看看是否发生重建表*/
54 
55     for(int i = 0;i<47;i++)
56         iht.insert_equal(i);
57     cout<<iht.size()<<endl;        //54
58     cout<<iht.buck_count()<<endl;    //97确实扩容了(重建)
59 
60     for (inti; i<iht.bucket_count();i++ )
61     {
62         int n = iht.elems_in_bucket(i); 
63         if(n!=0)
64             cout<<"bucket["<<i<<"] has"<<n<<" elems."<<endl;
65     }
66     /*打印的结果
67     bucket[2]到bucket[11]的节点个数为2
68     其余的bucket[0]~bucket[47]的节点个数为1
69     此外,bucket[53],[55],[59],[63]的节点个数均为1*/
70 
71     /*以迭代器变量hashtable,将所有节点打印出来*/
72     ite = iht.begin();
73     for(int i = 0;i<iht.size();i++,ite++)
74         cout<< *ite<<<' ';
75     cout<<endl;
76 
77     cout<<*(iht.find(2))<<endl;//2
78     cout<<iht.count(2)<<endl;//2
79     return 0;
80 }

 

转载于:https://www.cnblogs.com/houjun/p/4923255.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值