我们有两个数组,任务是比较两个数组,并使用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