Elements present in first array and not in second using STL in C++

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++


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.


OutputIterator set_difference (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result);

Below is the implementation of the above approach:





// C++ simple program to
// find elements which are
// not present in second array
#include <bits/stdc++.h>
using namespace std;
// Function for finding
// elements which are there
// in a[] but not in b[].
void findMissing(int a[], int b[],
                 int n, int m)
    // Declare a vector to store the result
    vector<int> v(n + m);
    // And an iterator to traverse the vector
    vector<int>::iterator it;
    // Sort the given arrays
    sort(a, a + n);
    sort(b, b + m);
    // Find the elements in a[]
    // which are not in b[]
    it = set_difference(a, a + n, b, b + m, v.begin());
    // Now resize the vector to the existing count
    v.resize(it - v.begin());
    // Print the results
    cout << "The elements in a[]"
         << " which are not in b[]:\n";
    for (it = v.begin(); it != v.end(); ++it)
        cout << *it << "  ";
    cout << endl;
// Driver code
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;



The elements in a[] which are not in b[]:
5  6

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.