# Find relative complement of two sorted arrays in C++

C++Server Side ProgrammingProgramming

Suppose we have two sorted arrays arr1 and arr2, there sizes are m and n respectively. We have to find relative complement of two arrays. It means that we need to find all those elements which are present in arr1, but not in arr2. So if the arrays are like A = [3, 6, 10, 12, 15], and B = [1, 3, 5, 10, 16], then result will be [6, 12, 15]

To solve this, we can use the set_difference function. As the problem is basically set difference operation.

## Example

Live Demo

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
int first[] = {3, 6, 10, 12, 15};
int second[] = {1, 3, 5, 10, 16};
int n = sizeof(first) / sizeof(first[0]);
vector<int> temp(5);
vector<int>::iterator it, ls;
sort(first, first + 5);
sort(second, second + 5);
cout << "First array :";
for (int i = 0; i < n; i++)
cout << " " << first[i];
cout << endl;
cout << "Second array :";
for (int i = 0; i < n; i++)
cout << " " << second[i];
cout << endl;
ls = set_difference(first, first + 5, second, second + 5, temp.begin());
cout << "The result of relative complement ";
for (it = temp.begin(); it < ls; ++it)
cout << " " << *it;
cout << endl;
}

## Output

First array : 3 6 10 12 15
Second array : 1 3 5 10 16
The result of relative complement 6 12 15
Published on 17-Dec-2019 15:45:23