How to find the intersection of two arrays in C++
Overview
The union of two sets, A and B, is the set of elements in A,B, or in both A and B.
Set has a property in which all the elements in the set are unique.
Example
A = {3,5,7 8,4,9}
B = {1,2,3,5,9,7,8,6}
A ∩ B = { 3, 5, 9, 7, 8 }
Code
#include <iostream>using namespace std;#define sizeOfA 6#define sizeOfB 8int findCommonElement(int setA[], int sizeOfSetA, int setB[], int sizeOfSetB){int commonElemnt =0;for(int i=0; i<sizeOfSetA; i++){for(int j=0; j<sizeOfSetB; j++){if(setA[i]==setB[j]){commonElemnt++;}}}}int *findIntersection(int setA[], int sizeOfSetA, int setB[], int sizeOfSetB, int commonElement){int *IntersectionArray;// find size of new Arrayint sizeOfIntersectionArray= commonElement;IntersectionArray= new int[sizeOfIntersectionArray];int k=0; // to insert elemnt in the union array we use this iteratorfor(int i=0; i<sizeOfSetB; i++){for(int j=0; j<sizeOfSetA; j++){if (setA[j]==setB[i]){IntersectionArray[k]=setA[j];k++;}}}return IntersectionArray;}int main(){int * IntersectionArray;// declare two array A and Bint A[sizeOfA] = {3,5,7,8,4,9};int B[sizeOfB] = {1,2,3,5,9,7,8,6};int commonElement=findCommonElement(A,sizeOfA, B,sizeOfB);// get number of Common Element of both arraysint sizeOfNewArray=commonElement-1;// calculate size ofnew ArrayIntersectionArray=findIntersection(A,sizeOfA,B,sizeOfB, commonElement);//Print the array elementcout<<"{ ";for(int i =0; i<sizeOfNewArray; i++){if(i==sizeOfNewArray-1){cout<<IntersectionArray[i]<<" }";}else{cout<<IntersectionArray[i]<<", ";}}return 0;}
Explanation
- Line 3 and 4: We define the size of
setAandsetB. - Line 5 to 18: We define the function
findCommonElementthat can find the count of the common elements between two sets. - Line 19 to 39: We define the function
findIntersectionthat can find the intersection of two setsetAandsetB. - Line 44 and 45: We define two arrays,
setAandsetB. - Line 48: We call the function
findIntersectionand save the array return by function in theIntersectionArraypointer variable. - Line 50 to 62: We print the intersection of
setAandsetB.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved