编写程序实现两个整数集合的基本运算: S1+S2 集合并运算 S1-S2 集合差运算 S1*S2 集合交运算 要求:输入整数集合{2 4 1 3 5}和{2 5 10},输出前者元素个数以及它们进行集合并、差、交运算后的结果。C++
时间: 2024-03-06 15:47:57 浏览: 17
好的,以下是 C++ 代码实现:
```cpp
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s1 = {2, 4, 1, 3, 5};
set<int> s2 = {2, 5, 10};
// 集合并运算
set<int> union_set;
set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(union_set, union_set.begin()));
// 集合差运算
set<int> difference_set;
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(difference_set, difference_set.begin()));
// 集合交运算
set<int> intersection_set;
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(intersection_set, intersection_set.begin()));
// 输出结果
cout << "集合s1的元素个数:" << s1.size() << endl;
cout << "集合s2的元素个数:" << s2.size() << endl;
cout << "集合并:";
for (auto x : union_set) {
cout << x << " ";
}
cout << endl;
cout << "集合差:";
for (auto x : difference_set) {
cout << x << " ";
}
cout << endl;
cout << "集合交:";
for (auto x : intersection_set) {
cout << x << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
集合s1的元素个数:5
集合s2的元素个数:3
集合并:1 2 3 4 5 10
集合差:1 3 4
集合交:2 5
```