
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Relative Complement of Two Sorted Arrays in C++
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
#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
Advertisements