Elements present in first array and not in second using STL in C++
Last Updated :
14 Jun, 2022
Given two arrays, the task is that we find numbers which are present in first array, but not present in the second array, using STL in C++ Examples:
Input: a[] = {1, 2, 3, 4, 5, 10}, b[] = {2, 3, 1, 0, 5}
Output: 4 10
Input:a[] = {4, 3, 5, 9, 11}, b[] = {4, 9, 3, 11, 10};
Output: 5
Approach: In STL, the set_difference() method can be used to find the ‘A-B’ where A is the first array and B is the second array. Syntax:
OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result);
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void findMissing( int a[], int b[],
int n, int m)
{
vector< int > v(n + m);
vector< int >::iterator it;
sort(a, a + n);
sort(b, b + m);
it = set_difference(a, a + n, b, b + m, v.begin());
v.resize(it - v.begin());
cout << "The elements in a[]"
<< " which are not in b[]:\n" ;
for (it = v.begin(); it != v.end(); ++it)
cout << *it << " " ;
cout << endl;
}
int main()
{
int a[] = { 1, 2, 6, 3, 4, 5 };
int b[] = { 2, 4, 3, 1, 0 };
int n = sizeof (a) / sizeof (a[0]);
int m = sizeof (b) / sizeof (b[1]);
findMissing(a, b, n, m);
return 0;
}
|
Output:
The elements in a[] which are not in b[]:
5 6
Time Complexity: O(nlogn + mlogm), used for sorting the given arrays
Auxiliary Space: O(n+m), extra space of size (n+m) used for creating vector
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...