文章目录
STL关联容器 set
集合容器(set):快速查找,不允许重复值
set 的特点:有序且不重复
1. 操作
1.1 使用迭代器遍历
#include <iostream>
#include <set>
using namespace std;
int main(){
// 迭代器遍历
set<int> s = {
1,5,3,7,3};
for(auto it = s.begin();it != s.end();++it){
cout << *it << " ";
}
cout << endl;
for(auto n:s){
cout << n << " ";
}
cout << endl;
}
结果为:
1 3 5 7
1 3 5 7
1.2 插入
将某一个数值插入到数组中
#include <iostream>
#include <set>
using namespace std;
int main(){
set<int> s = {
1,5,3,7,3};
for(auto n:s){
cout << n << " ";
}
cout << endl;
// 添加数据
// pair<set<int>::iterator,bool> res = s.insert(10);
auto res = s.insert(10); // 插入数字10
if(res.second){
// 插入成功即插入不重复,res.second为true
cout << *(res.first) << "插入成功" << endl; // *(res.first)是具体数值
}else{
// 插入失败即插入数值重复
cout << "插入失败" << endl