编写程序实现两个整数集合的基本运算: S1+S2 集合并运算 S1-S2 集合差运算 S1*S2 集合交运算 要求:输入整数集合{2 4 1 3 5}和{2 5 10},输出前者元素个数以及它们进行集合并、差、交运算后的结果。c++实现
时间: 2024-05-16 20:13:43 浏览: 106
以下是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};
// 集合并运算
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 it = S_union.begin(); it != S_union.end(); ++it) {
cout << *it << " ";
}
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 it = S_diff.begin(); it != S_diff.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// 集合交运算
set<int> S_intersection;
set_intersection(S1.begin(), S1.end(), S2.begin(), S2.end(), inserter(S_intersection, S_intersection.begin()));
cout << "S1*S2: ";
for (auto it = S_intersection.begin(); it != S_intersection.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// 元素个数
cout << "S1元素个数:" << S1.size() << endl;
return 0;
}
```
输出结果为:
```
S1+S2: 1 2 3 4 5 10
S1-S2: 1 3 4
S1*S2: 2 5
S1元素个数:5
```
阅读全文