- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

# How to find common elements between two Vectors using STL in C++?

In this tutorial, we will be discussing a program to understand how to find common elements between two vectors using STL in C++.

To find the common elements between two given vectors we will be using the set_intersetion() method.

## Example

#include <bits/stdc++.h> using namespace std; int main(){ //defining the vectors vector<int> vector1 = { 1, 45, 54, 71, 76, 12 }; vector<int> vector2 = { 1, 7, 5, 4, 6, 12 }; sort(vector1.begin(), vector1.end()); sort(vector2.begin(), vector2.end()); 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; vector<int> v(vector1.size() + vector2.size()); vector<int>::iterator it, st; //finding the common elements 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; }

## Output

First Vector: 1 12 45 54 71 76 Second Vector: 1 4 5 6 7 12 Common elements: 1, 12,

- Related Questions & Answers
- How to find common elements between two Arrays using STL in C++?
- How to join two Vectors using STL in C++?
- How to find different elements between two string vectors in R?
- How to find the number of common words between two string vectors in R?
- How to find the common elements in multiple vectors in R?
- How to find the common elements between two or more arrays in JavaScript?
- How to find the covariance between two vectors in R?
- How to create a sequence of values between two vectors in R using corresponding elements?
- Java Program to Find Common Elements in Two ArrayList
- Find the common elements between two columns of an R dataframe.
- JavaScript Program for find common elements in two sorted arrays
- How to compute pairwise distance between two vectors in PyTorch?
- How to find the cross product of two vectors in R by adding the elements?
- How to find the union of two vectors in R?
- Working with Array and Vectors using STL in C++

Advertisements