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