c++ 中的 set 如何进行集合运算
导读:在 C++ 中,std::set 是一个关联容器,它包含一组唯一的对象。你可以使用 std::set 进行集合运算,例如并集、交集和差集。以下是如何使用 std::set 进行这些操作的示例: #include <iostream&g...
在 C++ 中,std::set
是一个关联容器,它包含一组唯一的对象。你可以使用 std::set
进行集合运算,例如并集、交集和差集。以下是如何使用 std::set
进行这些操作的示例:
#include <
iostream>
#include <
set>
int main() {
// 创建两个集合
std::set<
int>
set1 = {
1, 2, 3, 4, 5}
;
std::set<
int>
set2 = {
4, 5, 6, 7, 8}
;
// 并集
std::set<
int>
union_set = set1;
// 复制 set1 到 union_set
union_set.insert(set2.begin(), set2.end());
// 插入 set2 的元素
std::cout <
<
"Union: ";
for (int num : union_set) {
std::cout <
<
num <
<
" ";
}
std::cout <
<
std::endl;
// 交集
std::set<
int>
intersection_set = set1;
// 复制 set1 到 intersection_set
intersection_set.intersection(set2);
// 计算交集
std::cout <
<
"Intersection: ";
for (int num : intersection_set) {
std::cout <
<
num <
<
" ";
}
std::cout <
<
std::endl;
// 差集
std::set<
int>
difference_set = set1;
// 复制 set1 到 difference_set
difference_set.difference(set2);
// 计算差集
std::cout <
<
"Difference: ";
for (int num : difference_set) {
std::cout <
<
num <
<
" ";
}
std::cout <
<
std::endl;
return 0;
}
输出结果:
Union: 1 2 3 4 5 6 7 8
Intersection: 4 5
Difference: 1 2 3
注意,std::set
会自动去除重复元素,所以并集和交集的结果中不会有重复的元素。而差集的结果中可能包含重复的元素,但在这个例子中,由于我们使用的是 std::set
,重复元素会被自动去除。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c++ 中的 set 如何进行集合运算
本文地址: https://pptw.com/jishu/710158.html