How to find common elements between two Vector using STL in C++?
Given two vectors, find common elements between these two vectors using STL in C++.
Example:
Input:
vec1 = {1, 45, 54, 71, 76, 12},
vec2 = {1, 7, 5, 4, 6, 12}
Output: {1, 12}Input:
vec1 = {1, 7, 5, 4, 6, 12},
vec2 = {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 Vectors using STL #include <bits/stdc++.h> using namespace std; int main() { // Get the vector vector<int> vector1 = { 1, 45, 54, 71, 76, 12 }; vector<int> vector2 = { 1, 7, 5, 4, 6, 12 }; // Sort the vector sort(vector1.begin(), vector1.end()); sort(vector2.begin(), vector2.end()); // Print the vector cout << "First Vector: "; for (int i = 0; i < vector1.size(); i++) cout << vector1[i] << " "; cout << endl; cout << "Second Vector: "; for (int i = 0; i < vector2.size(); i++) cout << vector2[i] << " "; cout << endl; // Initialise a vector // to store the common values // and an iterator // to traverse this vector vector<int> v(vector1.size() + vector2.size()); vector<int>::iterator it, st; it = set_intersection(vector1.begin(), vector1.end(), vector2.begin(), vector2.end(), 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 Vector: 1 12 45 54 71 76 Second Vector: 1 4 5 6 7 12 Common elements: 1, 12,
Recommended Posts:
- How to find the sum of elements of a Vector using STL in C++?
- How to find common elements between two Arrays using STL in C++?
- Common Subtleties in Vector STLs
- Get first and last elements from Array and Vector in CPP
- Count elements in a vector that match a target value or condition
- How to find the maximum element of a Vector using STL in C++?
- How to find the minimum and maximum element of a Vector using STL in C++?
- Find and print duplicate words in std::vector<string> using STL functions
- vector::crend() & vector::crbegin() with example
- vector::front() and vector::back() in C++ STL
- vector::push_back() and vector::pop_back() in C++ STL
- vector::empty() and vector::size() in C++ STL
- vector :: cbegin() and vector :: cend() in C++ STL
- Find set of m-elements with difference of any two elements is divisible by k
- vector::at() and vector::swap() in C++ STL
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.



