前言
stl系列主要讲述有关stl的文章,使用STL可以大大提高步调开发的效率和代码的可维护性,且在算法角逐中,STL可以帮助我们更方便地实现各种算法。提高我们的效率。
set/multiset容器
要使用set/multiset要头文件set
set/multiset(集合/多重集)属于关联式容器,底层布局使用二叉树实现的
set/multiset的特点是:所有的元素在插入时会被自动排序
set/multiset的区别是:set容器不答应有重复的元素,而multiset容器答应有重复的数据
一.set构造和赋值和删除
- set<int> s1;//建立一个空集合
- s1.insert(3);//加入元素3
- s1.insert(4);
- s1.insert(1);
- s1.insert(9);
- s1.insert(0);
- s1.insert(3);
- for (auto i = s1.begin(); i != s1.end(); i++) {//遍历元素
- cout << *i << " ";
- }
- cout << "\n";
- //因为已经被排好序所以输出为从大到小
- set<int> s2 = s1;//将s1复制给s2
- for (auto i = s2.begin(); i != s2.end(); i++) {
- cout << *i << " ";
- }
- cout << "\n";
- set<int> s3(s2);//将s2复制给s3
- s1.insert(3);
- for (auto i = s3.begin(); i != s3.end(); i++) {
- cout << *i << " ";
- }
- cout << "\n";
- s3.erase(s3.begin());//删除第一个元素
- s3.erase(3);//删除元素3
- s3.erase(s3.begin(), s3.end());//删除所有元素
- s2.clear();//清除所有元素
复制代码 二.set容器的巨细与交换
- s1.size();//返回容器中的元素个数
- s2.empty();//判断容器是否为空
- s3.swap(s4);//交换两个集合容器,数据类型相同才行
复制代码 三.set容器的查找与统计
- s1.find(n);//查找元素n是否存在如果存在就返回该元素的迭代器,若不存在就返回set.end()
- s2.count(n);//统计n的个数,因为set中不能重复所以只能为0或1
- set<int>::iterator pos = s1.find(99);
- if (pos != s1.end()) {
- cout << "找到了" << endl;
- }
- else {
- cout << "未找到" << endl;
- }
复制代码 四.set与multiset容器的区别
1.muitise是set集合容器的一种,其拥有set的全部内容,在此根本上,multiset还具备了可以保存可以重复保存元>素的功能,因此会有略微和set的差别
2.multiset容器在实行insert()时只要数据不是非法数据和空数据,insert()就总能实行,无论是一个数据还是一段数据
3.multiset容器中的find()等函数会返回和参数匹配的第一个元素的迭代器,纵然存在多个元素也只是返回第一个
- #include<iostream>
- #include<set>
- using namespace std;
- int main() {
- multiset<int> s1;
- s1.insert(3);
- s1.insert(4);
- s1.insert(1);
- s1.insert(9);
- s1.insert(0);
- s1.insert(3);
- for (auto i = s1.begin(); i != s1.end(); i++) {
- cout << *i << " ";
- }
- cout << "\n";
- multiset<int> s2 = s1;
- for (auto i = s2.begin(); i != s2.end(); i++) {
- cout << *i << " ";
- }
- cout << "\n";
- multiset<int> s3(s2);
- s1.insert(3);
- for (auto i = s3.begin(); i != s3.end(); i++) {
- cout << *i << " ";
- }
- cout << "\n";
- cout << *s1.find(1) << endl;//这样是找不到的,这样找出来的是元素不是而不是位置
- int a = 1;//记录位置从1开始
- for (multiset<int>::iterator i = s1.begin(); i != s1.find(1); i++, a++);
- cout << a << endl;
- return 0;
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |