【STL——set与multiset容器】
·
引入
set和multiset是C++ STL中的两种关联容器,基于红黑树(平衡二叉树)实现,用于存储一组有序的元素。两者的主要区别在于元素的唯一性:
set中的元素必须唯一,不允许重复。
multiset允许存储重复的元素。
set
按惯例先添头文件
#include< set>
构造与赋值
set<int> st; //默认构造函数
set<int> st1(st); //拷贝构造函数
set<int> st2 = st; //重载等号操作符(也属拷贝构造函数)
set<int> st3;
st3 = st2; //赋值构造函数
插入与删除

void test() {
set<int> s1;
s1.insert(10);
s1.insert(90);
s1.insert(30);
s1.insert(20);
printSet(s1); //默认顺序输出:10、20、30、90
s1.erase(s1.begin()); //删除s1的第一个元素(10)
printSet(s1); //输出:20、30、90
s1.erase(30); //删除30
printSet(s1); //输出:20、90
s1.clear(); //清空
printSet(s1); //无输出
}
大小与交换

void test() {
set<int> s1 = { 10,90,30 }; //简便写法
printSet(s1); //默认顺序输出:10、30、90
cout <<"s1现在的大小为:" <<s1.size() << endl; //size=3
s1.erase(s1.begin()); //删除s1的第一个元素(10)
printSet(s1); //输出:30、90
cout << "s1现在的大小为:" << s1.size() << endl; //size=2
set<int> s2 = { 20,39,48,10 };
s2.swap(s1);
printSet(s1); //输出:10、20、39、48
s1.clear(); //清空
cout << "s1现在的大小为:" << s1.size() << endl; //size=0
if (s1.empty()) {
cout << "s1为空" << endl;
}
else {
cout << "s1不为空" << endl;
}
printSet(s1); //无输出
}
查找与统计

void test() {
set<int> s1 = { 10,90,30 }; //简便写法
//set<int>::iterator i=s1.find(90);
auto i=s1.find(90); //两种写法都可以
if (i != s1.end()) {
cout << *i << endl;
}
else {
cout << "未找到该元素" << endl;
}
cout <<s1.count(30)<< endl; //30仅有1个,输出1
s1.insert(30);
s1.insert(30);
cout << s1.count(30) << endl; //set不允许有重复元素出现,仍输出1
}
Multiset
Multiset允许存储相同元素,但在使用find()函数返回时返回的是参数匹配的第一个元素的迭代器,即存在多个相同元素时返回第一个。如果没有符合的参数则结束迭代器。
此外,在insert()时还能插入一段数据。
void test() {
multiset<int> ms;
ms.insert(20);
ms.insert(90);
ms.insert(10);
ms.insert(20);
ms.insert(70);
printSet(ms); //输出:10、20、20、70、90
int it = 0;
for (auto i = ms.begin(); i != ms.find(70); i++, it++) {}
cout << "发现20的位置在" << it << endl; //输出:3
multiset<int> ms1;
auto i = ms.begin();
i++;
i++;
ms1.insert(ms.begin(), i); //这里和上篇相同,不能直接给begin做加减(++可以,不能+2之类的)
printSet(ms1); //复制[0,2),也就是下标为0和1的元素,输出:10、20
}
此外还有pos()、lower_bound()、upper_bound()等函数:
void test() {
multiset<int> m = { 1,7,6,9,5,8,3,5,9,6,8 };
cout<<m.count(5)<<endl; //输出:2
int pos = 0;
for (auto i = m.begin(); i != m.find(9); i++, pos++);
//multiset自动排序m={1,3,5,5,6,6,7,8,8,9}
cout <<pos<<endl; //输出首个9的位置:9
cout << "-----------------------------" << endl;
auto pos1 = m.lower_bound(7); //大于等于7的最小值
cout << *pos1 << endl;
cout << "-----------------------------"<<endl;
auto pos2 = m.upper_bound(1); //大于1的最小值
cout << *pos2 << endl;
}
更多推荐
所有评论(0)