用c++代码写集合的交,差,并运算
时间: 2023-07-16 10:13:57 浏览: 61
下面是使用 C++ 实现集合的交、差和并运算的示例代码:
```c++
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s1 = {1, 2, 3};
set<int> s2 = {2, 3, 4};
// 求交集
set<int> intersection;
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(intersection, intersection.begin()));
cout << "Intersection: ";
for (const auto &x : intersection) {
cout << x << " ";
}
cout << endl;
// 求差集
set<int> difference;
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(difference, difference.begin()));
cout << "Difference: ";
for (const auto &x : difference) {
cout << x << " ";
}
cout << endl;
// 求并集
set<int> unionSet;
set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(unionSet, unionSet.begin()));
cout << "Union: ";
for (const auto &x : unionSet) {
cout << x << " ";
}
cout << endl;
return 0;
}
```
输出结果:
```
Intersection: 2 3
Difference: 1
Union: 1 2 3 4
```
在上面的代码中,我们使用了 C++ STL 中的 set 容器和 set_intersection()、set_difference() 和 set_union() 算法实现了集合的交、差和并运算。其中,set_intersection() 函数求两个集合的交集,set_difference() 函数求两个集合的差集,set_union() 函数求两个集合的并集。