
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to find common elements between two Arrays using STL in C++?
In this tutorial, we will be discussing a program to understand how to find common elements between two arrays using STL in C++.
To find the common elements between two given arrays we will be using the set_intersetion() method.
Example
#include <bits/stdc++.h> using namespace std; int main(){ //defining the array int arr1[] = { 1, 45, 54, 71, 76, 12 }; int arr2[] = { 1, 7, 5, 4, 6, 12 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); sort(arr1, arr1 + n1); sort(arr2, arr2 + n2); cout << "First Array: "; for (int i = 0; i < n1; i++) cout << arr1[i] << " "; cout << endl; cout << "Second Array: "; for (int i = 0; i < n2; i++) cout << arr2[i] << " "; cout << endl; vector<int> v(n1 + n2); vector<int>::iterator it, st; //finding the common elements it = set_intersection(arr1, arr1 + n1, arr2, arr2 + n2, v.begin()); cout << "\nCommon elements:\n"; for (st = v.begin(); st != it; ++st) cout << *st << ", "; cout << '\n'; return 0; }
Output
First Array: 1 12 45 54 71 76 Second Array: 1 4 5 6 7 12 Common elements: 1, 12,
- Related Articles
- How to find common elements between two Vectors using STL in C++?
- Java Program to Find Common Elements Between Two Arrays
- How to find the common elements between two or more arrays in JavaScript?
- C++ Program to find the common elements from two arrays
- Python Program to Find Common Elements in Two Arrays
- C# program to find common elements in three arrays using sets
- Golang Program to find the common elements from two arrays
- C# program to find common elements in three sorted arrays
- JavaScript Program for find common elements in two sorted arrays
- Find common elements in three sorted arrays in C++
- How to find common elements from arrays in android listview?
- Counting elements in two arrays using C++
- intersection_update() in Python to find common elements in n arrays
- Java program to find common elements in three sorted arrays
- Python program to find common elements in three sorted arrays?

Advertisements