5、编写程序实现两个整数集合的基本运算:S1+S2 集合并运算 S1-S2 集合差运算 S1*S2 集合交运算 要求:输入整数集合{2 4 1 3 5}和{2 5 10},输出前者元素个数以及它们进行集合并、差、交运算后的结果。用C++写出代码
时间: 2024-05-14 13:19:49 浏览: 111
以下是用C++实现的代码:
```c++
#include<iostream>
#include<set>
using namespace std;
int main()
{
set<int> s1 = {2, 4, 1, 3, 5}; // 定义集合S1
set<int> s2 = {2, 5, 10}; // 定义集合S2
// 集合并运算
set<int> s_union;
set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(s_union, s_union.begin()));
// 集合差运算
set<int> s_diff;
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(s_diff, s_diff.begin()));
// 集合交运算
set<int> s_intersection;
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(s_intersection, s_intersection.begin()));
// 输出结果
cout << "S1的元素个数为:" << s1.size() << endl;
cout << "S2的元素个数为:" << s2.size() << endl;
cout << "S1和S2的集合并为:";
for(auto it = s_union.begin(); it != s_union.end(); it++)
cout << *it << " ";
cout << endl;
cout << "S1和S2的集合差为:";
for(auto it = s_diff.begin(); it != s_diff.end(); it++)
cout << *it << " ";
cout << endl;
cout << "S1和S2的集合交为:";
for(auto it = s_intersection.begin(); it != s_intersection.end(); it++)
cout << *it << " ";
cout << endl;
return 0;
}
```
输出结果为:
```
S1的元素个数为:5
S2的元素个数为:3
S1和S2的集合并为:1 2 3 4 5 10
S1和S2的集合差为:1 3 4
S1和S2的集合交为:2 5
```
阅读全文