How to obtain shared elements within two Vector using STL in C++?
In this article, we will be discussing how to obtain shared elements between two vectors using STL in C++. To find this we are not writing any algorithm. We have methods defined STL library under algorithm does this stuff.
Example:
Input:
vec1 = {12, 35, 44, 54, 23, 24,87},
vec2 = {12, 27, 65, 44, 26, 24}
Output: {12, 44,24}
Input:
vec1 = {12, 17, 25, 74, 60, 52,11},
vec2 = {60, 25, 11,39}
Output: {60, 25, 11}
How to find shared element:
We are going to use predefined function that has been described in STL algorithms this function is set_intersection() . Using this function we will get our output.
Syntax :
auto lastPointer = std::set_intersection (vector1->start,
vector1->end,vector2->start, vector2->end, outpur vector->Start);
Implementation :
#include<iostream>
#include<vector>
#include <algorithm>
int main()
{
// INtialize and store the vector
std::vector<int> vec1 = { 1, 24, 54, 71, 76, 12 };
std::vector<int> vec2 = {12, 27, 65, 76, 26, 24};
// We need to sort the vector to find the interaction point with
//this perticular algorithm
std::sort(vec1.begin(), vec1.end());
std::sort(vec2.begin(), vec2.end());
// Printout the vector vec1 and vec 2
std::cout << "Vec1 : ";
for (int i = 0; i < vec1.size(); i++)
std::cout << vec1.at(i) << " ";
std::cout << std::endl;
std::cout << "Vec2 : ";
for (int i = 0; i < vec2.size(); i++)
std::cout << vec2.at(i) << " ";
std::cout << std::endl;
// Initialise the output vector with size of vec1+vec2;
std::vector<int> output(vec1.size()+vec2.size());
auto last = std::set_intersection(vec1.begin(),vec1.end(),
vec2.begin(),vec2.end(),output.begin());
std::cout << "\n Shared elements: ";
for ( auto it = output.begin(); it != last; it++)
std::cout << *it << " ";
std::cout<<std::endl;
return 0;
}
Post a Comment: