STL系列之六 set与hash_set

set和hash_set是STL中比较重要的容器,有必要对其进行深入了解。在STL中,set是以红黑树(RB-tree)作为底层数据结构的,hash_set是以Hash table(哈希表)作为底层数据结构的。set可以在时间复杂度为O(logN)情况下插入、删除和查找数据。hash_set操作的时间复杂度则比较复杂,这取决于哈希函数和哈希表的负载情况。下面列出set和hash_set的常用函数:

 

set和hase_set的更多函数请查阅MSDN

 

set的使用范例如下(hash_set类似):

[cpp]  view plain copy
  1. // by MoreWindows( http://blog.csdn.net/MoreWindows )  
  2. #include <set>  
  3. #include <ctime>  
  4. #include <cstdio>  
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     printf("--set使用 by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");  
  10.     const int MAXN = 15;  
  11.     int a[MAXN];  
  12.     int i;  
  13.     srand(time(NULL));  
  14.     for (i = 0; i < MAXN; ++i)  
  15.         a[i] = rand() % (MAXN * 2);  
  16.   
  17.     set<int> iset;     
  18.     set<int>::iterator pos;   
  19.   
  20.     //插入数据 insert()有三种重载  
  21.     iset.insert(a, a + MAXN);  
  22.   
  23.     //当前集合中个数 最大容纳数据量  
  24.     printf("当前集合中个数: %d     最大容纳数据量: %d\n", iset.size(), iset.max_size());  
  25.   
  26.     //依次输出  
  27.     printf("依次输出集合中所有元素-------\n");  
  28.     for (pos = iset.begin(); pos != iset.end(); ++pos)  
  29.         printf("%d ", *pos);  
  30.     putchar('\n');  
  31.   
  32.     //查找  
  33.     int findNum = MAXN;  
  34.     printf("查找 %d是否存在-----------------------\n", findNum);  
  35.     pos = iset.find(findNum);  
  36.     if (pos != iset.end())  
  37.         printf("%d 存在\n", findNum);  
  38.     else  
  39.         printf("%d 不存在\n", findNum);  
  40.   
  41.     //在最后位置插入数据,如果给定的位置不正确,会重新找个正确的位置并返回该位置  
  42.     pos  = iset.insert(--iset.end(), MAXN * 2);   
  43.     printf("已经插入%d\n", *pos);  
  44.   
  45.     //删除  
  46.     iset.erase(MAXN);  
  47.     printf("已经删除%d\n", MAXN);  
  48.   
  49.     //依次输出  
  50.     printf("依次输出集合中所有元素-------\n");  
  51.     for (pos = iset.begin(); pos != iset.end(); ++pos)  
  52.         printf("%d ", *pos);  
  53.     putchar('\n');  
  54.     return 0;  
  55. }  

运行结果如下:

 

下面试下在set中使用类(结构体也可以类似这样做)。这个类很简单,只有一个成员变量,及设置和获取这个成员变量的成员函数。

[cpp]  view plain copy
  1. //在set中使用类要重载‘<’并实现拷贝构造函数  
  2. // by MoreWindows( http://blog.csdn.net/MoreWindows )  
  3. #include <set>  
  4. #include <ctime>  
  5. #include <cstdio>  
  6. using namespace std;  
  7. class Node  
  8. {  
  9. public:  
  10.     Node(int nAge = 0)  
  11.     {  
  12.         m_nAge = nAge;  
  13.     }  
  14.     Node(const Node &na)  //拷贝构造函数  
  15.     {  
  16.         m_nAge = na.GetAge();  
  17.     }  
  18.     int GetAge()  
  19.     {  
  20.         return m_nAge;  
  21.     }  
  22. private:  
  23.     int m_nAge;  
  24. };  
  25. //不能写成类的成员函数  
  26. inline bool operator < (const Node &na, const Node &nb)   
  27. {  
  28.     return na.GetAge() < nb.GetAge();  
  29. }  
  30. int main()  
  31. {  
  32.     int i;  
  33.     set<Node> nset;  
  34.     for (i = 0; i < MAXN; ++i)  
  35.         nset.insert(Node(i));  
  36.     return 0;  
  37. }  

编译,直接报了3个错误!!1个在拷贝构造函数,2个在operator<()函数。如下图所示:

3个错误都是一样的:

error C2662: “Node::GetAge”: 不能将“this”指针从“const Node”转换为“Node &” 转换丢失限定符

这是怎么回事呀?分析下,拷贝构造函数与operator<()函数出错,错误都指向了GetAge()函数,有点古怪,比较下它们与GetAge()函数,可以发现最大的不同点在于这2个函数都用到了const而GetAge()函数没有使用const。难道是这个导致报错了吗?先给GetAge()函数加个const看看,如下:

       int GetAge()  const //增加这个const

       {

              returnm_nAge;

       }

再编译,不报错了。再查下资料,原因如下——因为那2个函数都使用了const修饰的对象,但GetAge()没有加上const以保证它不修改对象,编译器认为这种写法是不安全的,所以就毫不犹豫报了个错误。

这种错误如果不亲身体会下,到笔试面试时很可能写了个错误程序而自己还处于一无所知中(死在这些小细节上最不值得)。另外,如果使用VC6.0则不会提示详细的错误信息——“转换丢失限定符”。

 

STL还为set提供了一些集合运算的函数,如交集set_intersection()、并集set_union()、差集set_difference()和对称差集set_symmetric_difference()。这些就不详细介绍了,有兴趣可以自己动手试一试。

下面开始对set和hash_set作个性能测试(Win7 +VS2008Release下)。

测试代码如下:

[cpp]  view plain copy
  1. // by MoreWindows( http://blog.csdn.net/MoreWindows )  
  2. #include <set>  
  3. #include <hash_set>  
  4. #include <iostream>  
  5. #include <ctime>  
  6. #include <cstdio>  
  7. #include <cstdlib>  
  8. using namespace std;  
  9. using namespace stdext;  //hash_set  
  10.   
  11. // MAXN个数据 MAXQUERY次查询  
  12. const int MAXN = 10000, MAXQUERY = 5000000;  
  13. int a[MAXN], query[MAXQUERY];  
  14.   
  15. void PrintfContainertElapseTime(char *pszContainerName, char *pszOperator, long lElapsetime)  
  16. {  
  17.     printf("%s 的%s操作 用时 %d毫秒\n", pszContainerName, pszOperator, lElapsetime);  
  18. }  
  19.   
  20. int main()  
  21. {  
  22.     printf("set VS hash_set 性能测试 数据容量 %d个 查询次数 %d次\n", MAXN, MAXQUERY);  
  23.     const int MAXNUM = MAXN * 4;  
  24.     const int MAXQUERYNUM = MAXN * 4;  
  25.     printf("容器中数据范围 [0, %d) 查询数据范围[0, %d)\n", MAXNUM, MAXQUERYNUM);  
  26.     printf("--by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");  
  27.       
  28.     //随机生成在[0, MAXNUM)范围内的MAXN个数  
  29.     int i;  
  30.     srand(time(NULL));  
  31.     for (i = 0; i < MAXN; ++i)  
  32.         a[i] = (rand() * rand()) % MAXNUM;  
  33.     //随机生成在[0, MAXQUERYNUM)范围内的MAXQUERY个数  
  34.     srand(time(NULL));  
  35.     for (i = 0; i < MAXQUERY; ++i)  
  36.         query[i] = (rand() * rand()) % MAXQUERYNUM;  
  37.   
  38.     set<int>       nset;  
  39.     hash_set<int> nhashset;  
  40.     clock_t  clockBegin, clockEnd;  
  41.   
  42.   
  43.     //insert  
  44.     printf("-----插入数据-----------\n");  
  45.   
  46.     clockBegin = clock();    
  47.     nset.insert(a, a + MAXN);   
  48.     clockEnd = clock();  
  49.     printf("set中有数据%d个\n", nset.size());  
  50.     PrintfContainertElapseTime("set""insert", clockEnd - clockBegin);  
  51.   
  52.     clockBegin = clock();    
  53.     nhashset.insert(a, a + MAXN);   
  54.     clockEnd = clock();  
  55.     printf("hash_set中有数据%d个\n", nhashset.size());  
  56.     PrintfContainertElapseTime("hase_set""insert", clockEnd - clockBegin);  
  57.   
  58.   
  59.     //find  
  60.     printf("-----查询数据-----------\n");  
  61.   
  62.     int nFindSucceedCount, nFindFailedCount;   
  63.     nFindSucceedCount = nFindFailedCount = 0;  
  64.     clockBegin = clock();   
  65.     for (i = 0; i < MAXQUERY; ++i)  
  66.         if (nset.find(query[i]) != nset.end())  
  67.             ++nFindSucceedCount;  
  68.         else  
  69.             ++nFindFailedCount;  
  70.     clockEnd = clock();  
  71.     PrintfContainertElapseTime("set""find", clockEnd - clockBegin);  
  72.     printf("查询成功次数: %d    查询失败次数: %d\n", nFindSucceedCount, nFindFailedCount);  
  73.       
  74.     nFindSucceedCount = nFindFailedCount = 0;  
  75.     clockBegin = clock();    
  76.     for (i = 0; i < MAXQUERY; ++i)  
  77.         if (nhashset.find(query[i]) != nhashset.end())  
  78.             ++nFindSucceedCount;  
  79.         else  
  80.             ++nFindFailedCount;  
  81.     clockEnd = clock();  
  82.     PrintfContainertElapseTime("hash_set""find", clockEnd - clockBegin);  
  83.     printf("查询成功次数: %d    查询失败次数: %d\n", nFindSucceedCount, nFindFailedCount);  
  84.     return 0;  
  85. }  

在数据容量100万,查询次数500万时,程序运行结果如下:

由于查询的失败次数太多,这次将查询范围变小使用再测试下:

由于结点过多,80多万个结点,set的红黑树树高约为19(2^19=524288,2^20=1048576),查询起来还是比较费时的。hash_set在时间性能上比set要好一些,并且如果查询成功的几率比较大的话,hash_set会有更好的表现。想知道为什么hash_set会有优良的性能表现,请看继集——《STL系列之九 探索hash_set》。

 

 

注1.   MSDN上讲set的erase()是有返回值的,但在VS2008中查看set的源代码,erase()函数的三个重载版本中,有二个返回值都为void即无返回值,另一个返回size_type。 可以通过http://msdn.microsoft.com/zh-cn/library/8h4a3515(v=VS.90).aspx查看MSDN上对set的erase()说明。

 

 

转载请标明出处,原文地址:http://blog.csdn.net/morewindows/article/details/7029587


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值