set也是一种容器,像vector,string这样,但它是树形容器。在物理结构上是二叉搜索树,逻辑上还是线性结构。set容器内元素不可重复,multiset内容器元素可以重复;这两个容器,插入的元素都是有序排列。
1.默认构造函数 | set |
2. 初始化列表 | set set |
3. 迭代器的方式 | set |
4. 拷贝构造 | set |
set |
|
1. = set 对象 | set s1 = s; |
2. = 初始化列表 | set s2 = { 3, 4, 5 } |
s1.empty(),为空返回1,不为空返回0 |
s1.size(),容器内元素个数 |
s.insert(3) | |
vector s.insert(v.begin(), v.end()); |
set s.erase(3);//直接删除元素3 |
set set s.erase(rml, rmr);//这个是删除2-4区间元素 |
set s = { 1,2,3,4,5 };
set::iterator it = s.find(3);//找到返回迭代器3
it = s.find(10);//找不到返回迭代器end()
//count()统计元素个数,因为set没有重复数,所以只会返回0,1
set s = { 1,2,3,4,5 };
for (int i = 0; i < 8; i += 2) {
cout << "元素:" << i << "的出现次数为 " << s.count(i) << endl;
}
//multiset可以有重复数,所以count()会正常出现数
multiset 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;
}
#include
#include
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;
}