编写C++程序实现两个整数集合的基本运算: S1+S2 集合并运算 S1-S2 集合差运算 S1*S2 集合交运算 要求:输入整数集合{2 4 1 3 5}和{2 5 10},输出前者元素个数以及它们进行集合并、差、交运算后的结果。
时间: 2024-05-14 21:19:00 浏览: 88
以下是实现上述功能的C++程序:
```cpp
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main() {
set<int> S1{2, 4, 1, 3, 5};
set<int> S2{2, 5, 10};
// 输出S1的元素个数
cout << "S1的元素个数为:" << S1.size() << endl;
// 集合并运算
set<int> S_union;
set_union(S1.begin(), S1.end(), S2.begin(), S2.end(), inserter(S_union, S_union.begin()));
cout << "S1和S2的并集为:";
for (auto x : S_union) {
cout << x << " ";
}
cout << endl;
// 集合差运算
set<int> S_diff;
set_difference(S1.begin(), S1.end(), S2.begin(), S2.end(), inserter(S_diff, S_diff.begin()));
cout << "S1和S2的差集为:";
for (auto x : S_diff) {
cout << x << " ";
}
cout << endl;
// 集合交运算
set<int> S_intersect;
set_intersection(S1.begin(), S1.end(), S2.begin(), S2.end(), inserter(S_intersect, S_intersect.begin()));
cout << "S1和S2的交集为:";
for (auto x : S_intersect) {
cout << x << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
S1的元素个数为:5
S1和S2的并集为:1 2 3 4 5 10
S1和S2的差集为:1 3 4
S1和S2的交集为:2 5
```
阅读全文