用c++编程:输入两个数组(数组元素个数自定),输出在两个数组中都不出现的元素 (如a[5]={2.34,5,6},b[6]={3,5,7,9,10-1},则输出2、4、6、3、7、9、10、-1)。
时间: 2024-02-06 22:10:51 浏览: 37
以下是用 C++ 实现的代码:
```cpp
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
vector<double> findUniqueElements(double arr1[], int n1, double arr2[], int n2) {
// 将数组1和数组2中的元素存储到两个无序集合中
unordered_set<double> set1(arr1, arr1 + n1);
unordered_set<double> set2(arr2, arr2 + n2);
// 定义一个空的 vector,用于存储在两个数组中都不存在的元素
vector<double> result;
// 遍历数组1中的元素,将不存在于数组2中的元素加入结果 vector 中
for (int i = 0; i < n1; i++) {
if (set2.find(arr1[i]) == set2.end()) {
result.push_back(arr1[i]);
}
}
// 遍历数组2中的元素,将不存在于数组1中的元素加入结果 vector 中
for (int i = 0; i < n2; i++) {
if (set1.find(arr2[i]) == set1.end()) {
result.push_back(arr2[i]);
}
}
return result;
}
int main() {
double arr1[] = {2.34, 5, 6};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
double arr2[] = {3, 5, 7, 9, 10.0 - 1};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
vector<double> result = findUniqueElements(arr1, n1, arr2, n2);
// 输出在两个数组中都不存在的元素
for (double x : result) {
cout << x << " ";
}
return 0;
}
```
在这个程序中,我们首先将数组1和数组2中的元素存储到两个无序集合中。然后,我们遍历数组1中的元素,并将不存在于数组2中的元素加入结果 vector 中。接着,我们遍历数组2中的元素,并将不存在于数组1中的元素加入结果 vector 中。最后,我们返回结果 vector,按照顺序输出其中的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)