STL:set用法总结

一:介绍

set是STL的关联式容器,以红黑树(Red-Black Tree)作为底层数据结构。自动去重,保证每个元素唯一,并对数据进行排序。

命名空间为std,所属头文件为<set>

二:常用操作

容量:
a.set中实际数据的数据:set.size()
b.set中最大数据的数量:set.max_size()
c.判断容器是否为空:set.empty()

修改:
a.插入数据:set.insert()
b.清空set元素:set.clear()
c.删除指定元素:set.erase(it)

迭代器:
a.set开始指针:set.begin()
b.set尾部指针:set.end() 注:最后一个元素的下一个位置,类似为NULL,不是容器的最后一个元素

三:存储

 1     //简单存储
 2     set<int> iSet;
 3     for (int i=0; i<10; i++)
 4     {
 5         iSet.insert(rand()%100);
 6     }
 7 
 8     //存储结构体
 9     struct Student1
10     {
11         char name[32];
12         int     age;
13         bool operator<(const Student1& tmp) const{
14             if(this->age < tmp.age)
15                 return true;   
16             return false;
17         }
18     };
19 
20     Student1 stu1;
21     strcpy(stu1.name, "woniu201");
22     stu1.age = 32;
23     Student1 stu2;
24     strcpy(stu2.name, "beijing");
25     stu2.age = 30;
26 
27      set<Student1> sSet;
28      sSet.insert(stu1);
29      sSet.insert(stu2);

四:遍历

1     for (set<int>::iterator it = iSet.begin(); it != iSet.end(); it++)
2     {
3         cout << *it << endl;
4     }

五:查找

1     set<int>::iterator it = find(iSet.begin(), iSet.end(), 24);
2     if (it != iSet.end())
3     {
4         cout << "found" << endl;
5     }
6     else
7     {
8         cout << "not found" << endl;
9     }

六:删除

1     for (set<int>::iterator it = iSet.begin(); it != iSet.end(); it++)
2     {
3         if (*it == 24)
4         {
5             it = iSet.erase(it);
6             it--;
7         }
8     }

扫码关注公众号

专注分享Java,C/C++,STL,Spring框架,mybatis框架,mysql,redis,分布式,高并发,设计模式,爬虫,docker,shell编程等相关技术,在这里一起探讨,一起学习,一起进步,不定期分享视频书籍资源,充分利用碎片化时间,让我们的技术之路更加有乐趣。

原文地址:https://www.cnblogs.com/woniu201/p/9856813.html