编写程序,输入两个集合 setA 和 setB,分别输出它们的交集、并集和差集 setA-setB
时间: 2023-04-01 22:04:46 浏览: 237
单片机学习资料 40个实验程序
您好,我可以回答您的问题。以下是程序的代码:
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> setA, setB;
set<int> intersection, unionSet, difference;
// 输入 setA 和 setB
int n, m;
cout << "请输入 setA 的元素个数:";
cin >> n;
cout << "请输入 setA 的元素:";
for (int i = ; i < n; i++) {
int x;
cin >> x;
setA.insert(x);
}
cout << "请输入 setB 的元素个数:";
cin >> m;
cout << "请输入 setB 的元素:";
for (int i = ; i < m; i++) {
int x;
cin >> x;
setB.insert(x);
}
// 计算交集
set_intersection(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(intersection, intersection.begin()));
cout << "交集为:";
for (auto it = intersection.begin(); it != intersection.end(); it++) {
cout << *it << " ";
}
cout << endl;
// 计算并集
set_union(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(unionSet, unionSet.begin()));
cout << "并集为:";
for (auto it = unionSet.begin(); it != unionSet.end(); it++) {
cout << *it << " ";
}
cout << endl;
// 计算差集
set_difference(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(difference, difference.begin()));
cout << "setA-setB 差集为:";
for (auto it = difference.begin(); it != difference.end(); it++) {
cout << *it << " ";
}
cout << endl;
return ;
}
阅读全文