使用C++ STL查找第一个数组中存在但第二个数组中不存在的元素
我们有两个数组,任务是比较这两个数组,并使用C++中的标准模板库(STL)查找第一个数组中存在但第二个数组中不存在的数字。
示例
Input: array1[ ] = {1,2,3,4,5,7}
array2[ ] = {2,3,4,5,6,8}
Output: 1, 7
Input: array1[ ] = {1,20,33,45,67}
array2[ ] = {1,12,13,114,15,13}
Output: 20,33,45,67以下程序中使用的方案如下:
- 在这个程序中,我们想要找到存在于第一个数组中但不存在于第二个数组中的元素。
- 为此,我们首先初始化两个变量。现在,我们将创建一个名为“find”的函数来查找存在于数组1中但不属于数组2的元素。
- 在函数中,我们将声明一个向量(向量与动态数组相同,具有在插入或删除元素时自动调整自身大小的能力)来存储结果,我们还将声明一个迭代器来遍历向量。
- 现在,我们将对数组进行排序,并使用set_difference()方法查找缺失的元素,根据结果调整向量的大小并存储值,然后打印解决方案。
在标准模板库(STL)中,我们可以使用set_difference()方法来查找“array1-array2”。两个集合的差集由存在于第一个集合中但在第二个集合中不存在的元素构成。函数复制的元素总是来自第一个范围,顺序相同。两个范围中的元素都应已排序。
语法
set_difference()的语法如下:
OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result);
算法
Start Step 1-> Create function for finding missing elements void find(int array1[], int array2[], int x, int y) Declare a vector which stores the result as vector<int> v(x + y) Declare an iterator traverse the vector as vector<int>::iterator it Sort the arrays sort array1 and sort array2 End Find the missing elements diff = set_difference(array1, array1 + x, array2, array2 + y, v.begin()) resize the vector to the existing count v.resize(diff - v.begin()) print the elements present in array1[] and not in array2[] for (diff = v.begin() diff != v.end() ++diff Print *diff End Step 2-> In main() Declare array as int array1and int array2 Declare variable x and y to calculate the size of array1 and array 2 as int x = size of array1 and int y = size of array2 Call the function as find(array1, array2, x, y)
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
int array1[] = { 1, 2, 3, 4, 5, 7 };
int array2[] = { 2, 3, 4, 5, 6, 8 };
int x = sizeof(array1) / sizeof(array1[0]);
int y = sizeof(array2) / sizeof(array2[1]);
find(array1, array2, x, y);
return 0;
}
// Creating function named “find” for finding missing elements
void find(int array1[], int array2[],
int x, int y) {
// Declaring a vector which stores the result
vector<int> v(x + y);
// Declaring an iterator traverse the vector
vector<int>::iterator it;
// Sorting the arrays
sort(array1, array1 + x);
sort(array2, array2 + y);
// Finding the missing elements
diff = set_difference(array1, array1 + x, array2, array2 + y, v.begin());
//resizing the vector to the existing count
v.resize(diff - v.begin());
cout << "The elements present in array1[] and not in array2[]:”;
for (diff = v.begin(); diff != v.end(); ++diff)
cout << *diff << " ";
cout << endl;
}输出
如果我们运行上面的代码,它将生成以下输出:
The elements present in array1[] and not in array2[]: 1,7
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP