set:集合库

发布时间 2023-04-22 16:00:54作者: linux星

#include <set>
using namespace std;
set<int> s1; // 定义一个空的set,元素类型为int
set<int> s2 = {1, 2, 3}; // 使用花括号进行初始化
set<int> s3(s2); // 使用拷贝构造函数进行初始化

#include <set>
using namespace std;
set<int> s = {1, 2, 3};
// 获取set的大小
int size = s.size();
// 判断set中是否包含某个元素
bool contains = s.count(2); // 判断set中是否包含元素2
// set的插入和删除
s.insert(4); // 在set中插入元素4
s.erase(2); // 删除set中的元素2
// set的遍历
for (auto it = s.begin(); it != s.end(); ++it) {
    cout << *it << " ";
}
for (int element : s) {
    cout << element << " ";
}

#include <set>
#include <algorithm>
using namespace std;
set<int> s = {3, 1, 4, 1, 5, 9};
// set的排序
// set是自动排序的,无需进行排序
// set的查找
auto it = s.find(4); // 查找4在set中的位置
if (it != s.end()) {
    cout << "4 found in set" << endl;
} else {
    cout << "4 not found" << endl;
}
// set的合并
set<int> s1 = {1, 2};
set<int> s2 = {2, 3};
s1.insert(s2.begin(), s2.end()); // 将s2中的元素合并到s1中
// set的交集、并集和差集
set<int> s3 = {2, 3};
set<int> s4;
set_intersection(s1.begin(), s1.end(), s3.begin(), s3.end(), inserter(s4, s4.begin())); // 获取s1和s3的交集,结果存储在s4中
set_union(s1.begin(), s1.end(), s3.begin(), s3.end(), inserter(s4, s4.begin())); // 获取s1和s3的并集,结果存储在s4中
set_difference(s1.begin(), s1.end(), s3.begin(), s3.end(), inserter(s4, s4.begin())); // 获取s1和s3的差集,结果存储在s4中