引入:
set 和数学中的集合相似,set 中不会出现值相同的元素。如果需要有相同元素的集合,需要使用 multiset。multiset 的使用方法与 set
的使用方法基本相同。
什么是集合?额可以看看数学书哈!或戳这里(遇事不会就百度):百度百科-验证
声明set:
set<储存的类型> 容器名。大多STL容器都怎么声明(例如vector)。
举例:set<int> st;(int型set),当然也可改为double char string等等。
当然别忘了头文件:#include<set>
PS:set会自动排序并去重,其中去重类似数学中的集合
插入与删除操作:
insert(x)
当容器中没有等价元素的时候,将元素 x 插入到set
中。erase(x)
删除值为 x 的 所有 元素,返回删除元素的个数。erase(pos)
删除迭代器为 pos 的元素,要求迭代器必须合法。erase(first,last)
删除迭代器在 [first,last) 范围内的所有元素。clear()
清空set
。
举个栗子:
#include<bits/stdc++.h>
using namespace std;
int main(){
set<int> s;
s.insert(1);
s.insert(3);
s.insert(2);
cout<<"现有元素\n";
for(int c:s){
cout<<c<<" ";
}
cout<<"\n";
s.erase(3);
cout<<"删除3后的现有元素\n";
for(int c:s){
cout<<c<<" ";
}
cout<<"\n";
cout<<"现在s.size()=="<<s.size()<<"\n";
s.clear();
if(s.empty()) cout<<"是空集\n";
return 0;
}
迭代器:
不说了,之前讲了好多次,不懂的戳这里C++STL容器入门1(迭代器Iterator)!_Rudy1124的博客-CSDN博客
这里就举个栗子:
#include<bits/stdc++.h>
using namespace std;
int main(){
set<int> s;
s.insert(1);
s.insert(3);
s.insert(2);
//第1种输出方式
set<int>::iterator i;//注意迭代器不能重名!!!
for(i=s.begin();i!=s.end();++i){
cout<<*i<<" ";//注意是会排序的
}
cout<<"\n";
//第2种输出方式
for(auto it=s.begin();it!=s.end();++it){
cout<<*it<<" ";
}
cout<<"\n";
//第3种输出方式
for(auto iter:s){
cout<<iter<<" ";
}
cout<<"\n";
//第4种倒序输出
set<int>::reverse_iterator reit;
for(reit=s.rbegin();reit!=s.rend();++reit){
cout<<*reit<<" ";
}
/*
output:
1 2 3
1 2 3
1 2 3
3 2 1
*/
return 0;
}
是不是很简单(偷笑》》》)
查找操作:
count(x)
返回set
内键为 x 的元素数量。find(x)
在set
内存在键为 x 的元素时会返回该元素的迭代器,否则返回end()
。lower_bound(x)
返回指向首个不小于给定键的元素的迭代器。如果不存在这样的元素,返回end()
。upper_bound(x)
返回指向首个大于给定键的元素的迭代器。如果不存在这样的元素,返回end()
。empty()
返回容器是否为空。size()
返回容器内元素个数。
PS:set自带的lower_bound(x)以及upper_bound(x)的复杂度均为O(longn),但是若对set使用的
#includ<algorithm>里的lower_bound以及upper_bound,复杂度为O(n)
#include<iostream>
#include<set>
using namespace std;
int main(){
set<int> s;
for(int ii=1;ii<=5;ii++){
int x;cin>>x;
s.insert(x);
}
for(auto it:s){
cout<<it<<" ";
}
cout<<endl;
auto i1=s.lower_bound(2);
cout<<*i1<<endl;
auto i2=s.upper_bound(4);
cout<<*i2<<endl;
/*
input:
1 2 4 5 6
output:
1 2 4 5 6
2
5
*/
return 0;
}
重载运算符:
set
在默认情况下的比较函数为<,若你要改变比较方式就要运用重载运算符。
注意是重载“()”;
struct cmp{
bool operator()(int a,int b){
return a>b;
}
};
set<int,cmp> s;
若还不理解戳这里:重载运算符operator详解_Rudy1124的博客-CSDN博客
最后的BB:
多些做题多些用,熟悉了就容易了,兄弟萌,加油哈哈哈!
文章尚有不足,欢迎dalao指正
感谢观看,点个赞吧,QAQ