🔥 特点:set 在元素插入时会自动排序
set 属于关联式容器、底层由二叉树实现
set vs. multiset: 前者不可以包含重复元素;后者可以
步骤零: 使用时需要包含头文件 #include<set>
void printList(list<int> &l) // 逐个元素打印
{
for (list<int>::iterator i = l.begin(); i!=l.end(); i++)
{
cout << *i << endl;
}
}
💜 set 构造与赋值
// 1. 默认构造
set <int> s1 = {0,1,3,2,4,8,5,6,7,9}; // 会自动排序
set <int> s11;
s11 = s1; // 赋值 0 1 2 3 4 5 6 7 8 9
// 2. 通过区间构造
set<int> s2(s1.begin(), s1.end());
// 3. 拷贝构造
set<int> s3(s1);
💜 set 插入和删除:insert、erase、clear
set <int> s1 = {0,1,3,2,4,8,5,6,7,9}; // 会自动排序
s1.insert(s1.begin(), -1); // -1 0 1 2 3 4 5 6 7 8 9 - l1.begin() 处插入 -1
s1.erase(s1.begin()); // 0 1 2 3 4 5 6 7 8 9 - s1.begin() 处删除,即最小值 -1
s1.erase(5); // 0 1 2 3 4 6 7 8 9 - 删除值 5
s1.clear();
💜 set 大小获取:empty、 size
set <int> s1 = {0,1,3,2,4,8,5,6,7,9};
cout << s1.empty() << endl; // 0
cout << s1.size() << endl; // 10
💜 set 元素统计:find、 count (set vs. multiset)
set<int> s1 = {0,1,3,2,4,4,4,8,5,6,7,9};
cout << *s1.find(4) << endl; // 4, find 返回迭代器 set<int>::iterator pos = s1.find(4);
cout << s1.count(4) << endl; // 1, 非 3 因为 set 中的元素是唯一的
multiset<int> s1 = {0,1,3,2,4,4,4,8,5,6,7,9};
cout << *s1.find(4) << endl; // 4, find 返回迭代器 multiset<int>::iterator pos = s1.find(4);
cout << s1.count(4) << endl; // 3,是 3 因为 multiset 中的元素非唯一的
💜 set 元素互换:swap
set <int> s1 = {0,1,3,2,4,8,5,6,7,9};
set <int> s2 = {-0,-1,-2,-3,-4,-5,-6,-7,-8,-9};
s1.swap(s2);
// s1: -9,-8,-7,-6,-5,-4,-3,-2,-1,-0
// s2: 0,1,2,3,4,5,6,7,8,9
💜 set 自定义排序:由大到小示例
#include<iostream>
#include<set>
using namespace std;
#include <algorithm>
class my_compare // 自定义排序
{
public:
bool operator()(int v1, int v2) // 仿函数,重载 () 运算
{
return v1 > v2;
}
};
void printSet(set<int, my_compare> &s) // 逐个元素打印
{
for(set<int, my_compare>::iterator i = s.begin(); i!=s.end(); i++)
{
cout << *i << endl;
}
}
int main()
{
set<int, my_compare> s1 = {0,1,3,2,4,4,4,8,5,6,7,9};
printSet(s1); // 9 8 7 6 5 4 3 2 1 0
return 0;
}
988

被折叠的 条评论
为什么被折叠?



