How to find common elements between two Arrays using STL in C++?
Given two arrays, find common elements between these two arrays using STL in C++.
Example:
Input:
arr1[] = {1, 45, 54, 71, 76, 12},
arr2[] = {1, 7, 5, 4, 6, 12}
Output: {1, 12}
Input:
arr1[] = {1, 7, 5, 4, 6, 12},
arr2[] = {10, 12, 11}
Output: {1, 4, 12}
Approach: Common elements can be found with the help of set_intersection() function provided in STL.
Syntax:
set_intersection (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result);
// C++ program to find common elements // between two Arrays using STL #include <bits/stdc++.h> using namespace std; int main() { // Get the array int arr1[] = { 1, 45, 54, 71, 76, 12 }; int arr2[] = { 1, 7, 5, 4, 6, 12 }; // Compute the sizes int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); // Sort the arrays sort(arr1, arr1 + n1); sort(arr2, arr2 + n2); // Print the array 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; // Initialise a vector // to store the common values // and an iterator // to traverse this vector vector<int> v(n1 + n2); vector<int>::iterator it, st; 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; } |
chevron_right
filter_none
Output:
First Array: 1 12 45 54 71 76 Second Array: 1 4 5 6 7 12 Common elements: 1, 12,
Recommended Posts:
- How to find common elements between two Vector using STL in C++?
- Find N'th item in a set formed by sum of two arrays
- How to find the sum of elements of an Array using STL in C++?
- Find elements of an Array which are Odd and Even using STL in C++
- How to find the sum of elements of a Vector using STL in C++?
- Find elements of an array which are divisible by N using STL in C++
- Find k maximum elements of array in original order
- Common Subtleties in Vector STLs
- Common Memory/Pointer Related bug in C Programs
- Common mistakes to be avoided in Competitive Programming in C++ | Beginners
- Move matrix elements in given direction and add elements with same value
- Sum of all elements between k1'th and k2'th smallest elements
- Why is a[i] == i[a] in C/C++ arrays?
- Arrays in C/C++
- How to join two Arrays using STL in C++?
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.
Improved By : shubham_singh



