这篇专栏记录的是STL中set的常用用法。
set是内部有序且不含重复元素的容器,可以用set保留元素本身而不考虑该元素的个数。代码如下:
#include <iostream>
#include <set>
using namespace std;
int main(){
//set是内部有序且不含重复元素的容器
//0.定义一个set容器
set<int> s;
set<int>::iterator it;
//1.插入元素
s.insert(5);
s.insert(4);
s.insert(3);
s.insert(4);
s.insert(6);
s.insert(7);
//2.遍历
cout << "2.遍历:";
for(it = s.begin(); it != s.end(); it++){
cout << *it << " ";
}
cout << endl;
//3.查找某个存在的元素
it = s.find(3);
if(it != s.end()){ //映射表中存在该元素
cout << "3.通过迭代器访问元素:" << *it << endl;
}
else{
cout << "3.映射表中不存在该元素" << endl;
}
//4.查找某个不存在的元素
it = s.find(8);
if(it != s.end()){ //映射表中存在该元素
cout << "4.通过迭代器访问元素:" << *it << endl;
}
else{
cout << "4.映射表中不存在该元素" << endl;
}
//5.删除指定元素
it = s.find(6);
s.erase(it);
//也可以直接s.erase(6);
s.erase(6);
cout << "5.删除元素\"6\"后遍历:";
for(it = s.begin(); it != s.end(); it++){
cout << *it << " ";
}
cout << endl;
//6.清空所有元素
s.clear();
cout << "6:清空所有元素后" << "size:" << s.size();
return 0;
}
氷鸢鸢鸢
2020.2.26