一.基础概念
set也是一种容器,像vector,string这样,但它是树形容器。在物理结构上是二叉搜索树,逻辑上还是线性结构。set容器内元素不可重复,multiset内容器元素可以重复;这两个容器,插入的元素都是有序排列。
二.基础用法
1.set对象创建
1.默认构造函数 | set<int> s1; |
2. 初始化列表 |
set<int> s2_1 = { 9,8,7,6,5 };//5 6 7 8 9 set<int> s2_2({ 9,8,7,7,6,5 }); // set不支持重复元素、multiset支持重复元素 |
3. 迭代器的方式 | set<int> s3(s2_1.begin(), s2_1.end()); |
4. 拷贝构造 | set<int> s4(s2_2); |
2.set赋值操作
set<int> s = { 9,8,5,2,1,1 }; | |
1. = set 对象 | set<int> s1; s1 = s; |
2. = 初始化列表 |
set<int> s2; s2 = { 3, 4, 5 } |
3.set大小操作
s1.empty(),为空返回1,不为空返回0 |
s1.size(),容器内元素个数 |
4.set数据插入insert()
s.insert(3) | |
vector<int> v = { 0, 5, 6, 9 ,8 }; s.insert(v.begin(), v.end()); |
5.set数据删除erase()
set<int> s = { 1,2,3,4,5 }; s.erase(3);//直接删除元素3 |
set<int>::iterator rml = s.find(2); set<int>::iterator rmr = s.find(4); s.erase(rml, rmr);//这个是删除2-4区间元素 |
6.set数据查找find()
set<int> s = { 1,2,3,4,5 };
set<int>::iterator it = s.find(3);//找到返回迭代器3
it = s.find(10);//找不到返回迭代器end()
7.set数据统计count()
//count()统计元素个数,因为set没有重复数,所以只会返回0,1
set<int> s = { 1,2,3,4,5 };
for (int i = 0; i < 8; i += 2) {
cout << "元素:" << i << "的出现次数为 " << s.count(i) << endl;
}
//multiset可以有重复数,所以count()会正常出现数
multiset<int> ms = { 1,1,1,1,1,1,4,4,4,4,4,2,2,2,2,2,2,2,6,6,6,6,6,8,8,8,5,5,5,5,5 };
for (int i = 0; i < 8; i += 2) {
cout << "元素:" << i << "的出现次数为 " << ms.count(i) << endl;
}
8.set排序
#include <iostream>
#include <set>
using namespace std;
class CGaGa {
public:
CGaGa() {
_name = "";
_priority = -1;
}
CGaGa(string name, int pri) : _name(name), _priority(pri) {}
bool operator<(const CGaGa& cgg) const {
return _priority < cgg._priority;
}
void print() const {
cout << "(" << _priority << ")" << _name << endl;
}
private:
string _name;
int _priority;
};
int main() {
set< CGaGa > s;
s.insert(CGaGa("C++算法零基础", 5));
s.insert(CGaGa("C++面向对象", 2));
s.insert(CGaGa("C++零基础语法", 1));
s.insert(CGaGa("C++数据结构", 3));
s.insert(CGaGa("C++STL", 4));
s.insert(CGaGa("C++项目实战(贪食蛇、扫雷、3D赛车)", 6));
for (set< CGaGa >::iterator it = s.begin(); it != s.end(); it++) {
(*it).print();
}
return 0;
}