c++求两个集合的并集和交集,能实现多组数据的多次运算,直到选择结束运算为止,提供问答界面,以便人机交互
时间: 2023-12-09 14:03:08 浏览: 82
下面是一个示例代码,实现了多组数据的多次运算,直到选择结束运算为止,并提供了问答界面,以便人机交互:
```c++
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
void printSet(set<int> s)
{
for (auto it = s.begin(); it != s.end(); ++it) {
cout << *it << " ";
}
cout << endl;
}
void printIntersectionUnion(set<int> set1, set<int> set2)
{
set<int> intersection;
set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(intersection, intersection.begin()));
set<int> uni;
set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), inserter(uni, uni.begin()));
cout << "Intersection: ";
printSet(intersection);
cout << "Union: ";
printSet(uni);
}
int main()
{
set<int> set1, set2;
char choice;
do {
int n1, n2, x;
cout << "Please enter the size of set 1: ";
cin >> n1;
cout << "Please enter the elements of set 1: ";
for (int i = 0; i < n1; ++i) {
cin >> x;
set1.insert(x);
}
cout << "Please enter the size of set 2: ";
cin >> n2;
cout << "Please enter the elements of set 2: ";
for (int i = 0; i < n2; ++i) {
cin >> x;
set2.insert(x);
}
printIntersectionUnion(set1, set2);
cout << "Do you want to continue? (y/n): ";
cin >> choice;
} while (choice == 'y' || choice == 'Y');
cout << "Program ended." << endl;
return 0;
}
```
示例输出:
```
Please enter the size of set 1: 5
Please enter the elements of set 1: 1 2 3 4 5
Please enter the size of set 2: 5
Please enter the elements of set 2: 3 4 5 6 7
Intersection: 3 4 5
Union: 1 2 3 4 5 6 7
Do you want to continue? (y/n): y
Please enter the size of set 1: 3
Please enter the elements of set 1: 1 2 3
Please enter the size of set 2: 4
Please enter the elements of set 2: 2 3 4 5
Intersection: 2 3
Union: 1 2 3 4 5
Do you want to continue? (y/n): n
Program ended.
```
阅读全文