编写程序,输入两个集合setA和setB,分别输出它们的交集、并集和差集setA-setB。
时间: 2023-04-02 14:02:12 浏览: 105
好的,我可以回答这个问题。以下是程序的代码:
```
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> setA, setB;
int num;
// 输入集合A
cout << "请输入集合A的元素个数:";
cin >> num;
cout << "请输入集合A的元素:";
for (int i = ; i < num; i++) {
int elem;
cin >> elem;
setA.insert(elem);
}
// 输入集合B
cout << "请输入集合B的元素个数:";
cin >> num;
cout << "请输入集合B的元素:";
for (int i = ; i < num; i++) {
int elem;
cin >> elem;
setB.insert(elem);
}
// 输出交集
cout << "集合A和集合B的交集为:";
set<int> intersection;
set_intersection(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(intersection, intersection.begin()));
for (auto elem : intersection) {
cout << elem << " ";
}
cout << endl;
// 输出并集
cout << "集合A和集合B的并集为:";
set<int> unionSet;
set_union(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(unionSet, unionSet.begin()));
for (auto elem : unionSet) {
cout << elem << " ";
}
cout << endl;
// 输出差集
cout << "集合A和集合B的差集为:";
set<int> difference;
set_difference(setA.begin(), setA.end(), setB.begin(), setB.end(), inserter(difference, difference.begin()));
for (auto elem : difference) {
cout << elem << " ";
}
cout << endl;
return ;
}
```
阅读全文