STL之set

本文最后更新于:2023年8月26日 晚上

  • set和multiset的区别在于容器里不能有重复元素

    a和b重复 <=> “a必须排在b前面” 和”b必须排在a前面” 都不成立

  • set插入元素可能不成功

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<set>//使用multiset和set使用该头文件
using namespace std;
int main()
{
set<int> st;
int a[10]={1,14,12,13,7,13,21,19,8,8};//不重复算,如8,13只算一次
for(int i=0;i<10;i++)
st.insert(a[i]);
cout<< st.size()<<endl;//输出存放的元素个数
set<int>::iterator i;
for(i=st.begin();i!=st.end();i++){
cout<<*i<<',';
}
cout<<endl;
pair<set<int>::iterator, bool> result = st.insert(12);
if( ! result.second ) cout<< * result.first<<" already exists. "<<endl;
else cout<< * result.first<< "inserted."<<endl;
return 0;
}

pair模板的用法

1
2
3
4
5
6
pair<set<int>::iteractor, bool>
//等价于
struct {
set<int>::iteractor first;
bool second;
}
1
2
3
4
5
pair<T1,T2>
struct{
T1 first;
T2 second;
}

STL之set
https://furthur509.github.io/2023/08/25/STL之set/
作者
Yang Mingxin
发布于
2023年8月25日
许可协议