使用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
廣告