std::Set

set集合容器实现了红黑树(Red-Black Tree)的平衡二叉检索树的的数据结构,

在插入元素时,它会自动调整二叉树的排列,把该元素放到适当的位置,以确保每个子树根节点的键值大于左子树所有节点的键值,而小于右子树所有节点的键值;

另外,还得确保根节点的左子树的高度与有字数的高度相等,

这样,二叉树的高度最小,从而检索速度最快。

它不会重复插入相同键值的元素,而采取忽略处理。
平衡二叉检索树的检索使用中序遍历算法,
检索效率高于vector、deque、和list的容器。
平衡二叉检索树在插入元素时,就会自动将元素按键值从小到大的顺序排列。
set<int>::iterator it;             // 定义前向迭代器  
set<int>::reverse_iterator rit;    // 定义反向迭代器
it = s.erase(it++);                // 删除
it = s.find(6);                    // 查找的元素  
s.count(a)                         // 是否在集合中

如果元素不是结构体,那么可以编写比较函数。下面的程序比较规则为按键值从大到小的顺序插入到集合中。

 1 #include<iostream>  
 2 #include<set>  
 3 using namespace std;  
 4 struct mycomp  
 5 { //自定义比较函数,重载“()”操作符  
 6     bool operator() (const int &a, const int &b)  
 7     {  
 8         if(a != b)  
 9             return a > b;  
10         else  
11             return a > b;  
12     }  
13 };  
14 int main()  
15 {  
16     set<int, mycomp> s; //采用比较函数mycomp  
17     s.insert(5); //第一次插入5,可以插入  
18     s.insert(1);  
19     s.insert(6);  
20     s.insert(3);  
21     s.insert(5); //第二次插入5,重复元素,不会插入  
22     set<int,mycomp>::iterator it;  
23     for(it = s.begin(); it != s.end(); it++)  
24         cout << *it << " ";  
25     cout << endl;  
26     return 0;  
27 }  
View Code

如果元素是结构体,那么可以直接把比较函数写在结构体内。

 1 [cpp] view plain copy
 2 #include<iostream>  
 3 #include<set>  
 4 #include<string>  
 5 using namespace std;  
 6 struct Info  
 7 {  
 8     string name;  
 9     double score;  
10     bool operator < (const Info &a) const // 重载“<”操作符,自定义排序规则  
11     {  
12         //按score由大到小排序。如果要由小到大排序,使用“>”即可。  
13         return a.score < score;  
14     }  
15 };  
16 int main()  
17 {  
18     set<Info> s;  
19     Info info;  
20   
21     //插入三个元素  
22     info.name = "Jack";  
23     info.score = 80;  
24     s.insert(info);  
25 
26     info.name = "Tom";  
27     info.score = 99;  
28     s.insert(info);  
29 
30     info.name = "Steaven";  
31     info.score = 60;  
32     s.insert(info);  
33   
34     set<Info>::iterator it;  
35     for(it = s.begin(); it != s.end(); it++)  
36         cout << (*it).name << " : " << (*it).score << endl;   
37     return 0;  
38 }  
39 /* 
40 运行结果: 
41 Tom : 99 
42 Jack : 80 
43 Steaven : 60 
44 */  
View Code

猜你喜欢

转载自www.cnblogs.com/osbreak/p/9206470.html
std
今日推荐