두 개의 배열이 있습니다. 작업은 두 배열을 비교하고 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 아래 프로그램에서 사용된 접근 방식은 다음과 같습니다. 다음 -
- 이 프로그램에서 첫 번째 배열에는 있지만 두 번째 배열에는 없는 요소를 찾고 싶습니다.
- 이 작업을 수행하기 위해 먼저 두 변수를 초기화합니다. 이제 배열 1에 있고 배열 2에는 없는 요소를 찾기 위해 "찾기"라는 함수를 만듭니다.
- 함수에서 우리는 결과를 저장하기 위해 벡터(벡터는 요소가 삽입되거나 삭제될 때 자동으로 크기를 조정할 수 있는 기능이 있는 동적 배열과 동일)를 선언하고 벡터를 순회하는 반복자를 선언할 것입니다.
- 이제 set_difference() 메서드를 사용하여 배열을 정렬하고 누락된 요소를 찾고 결과에 따라 벡터 크기를 조정하고 값을 저장한 다음 솔루션을 인쇄합니다.
STL(Standard Template Library)에서는 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