set与hash_set

原文:http://blog.csdn.net/morewindows/article/details/7029587

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 plaincopy
 
  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. }  

运行结果如下:

 

 

 

posted @ 2015-04-24 19:33  止战  阅读(598)  评论(0编辑  收藏  举报