Open In App

How to Find the Intersection of a Vector and a Set in C++?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, vectors and sets are two data containers that can store a collection of elements. In this article, we will learn how to find the intersection of a vector and a set in C++.

Example

Input:
myVector = { 1, 4, 2, 3, 7, 6, 5}
myset = { 1, 2, 3, 5, 7, 11, 12 }

Output:
Intersection = {1, 2, 3, 4, 5, 7}

Find the Intersection of a Vector and a Set in C++

Intersection represents the common elements or values present in both data structures. To find the intersection of a vector and a set, we can use the std::set_intersection method that finds the intersection between two sorted ranges, adds the data in the given container, and returns the iterator to the last.

Syntax of set_intersection()

set_intersection (first1, first2, last1, last2, result);

C++ Program to Find the Intersection of a Vector and a Set

Here we will see the implementation for finding intersection of a vector and set.

C++




// C++ Program to Find Common Elements or intersection
// Between a Vector and a Set
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
  
using namespace std;
  
int main()
{
    // Define two containers: a vector and a set
    vector<int> myVector = { 1, 4, 2, 3, 7, 6, 5 };
    set<int> mySet = { 1, 2, 3, 5, 7, 11, 12 };
  
    sort(myVector.begin(), myVector.end());
  
    // Initialize a vector to store common elements
    vector<int> common_elements;
    // Find the common elements between vec1 and mySet
    set_intersection(myVector.begin(), myVector.end(),
                     mySet.begin(), mySet.end(),
                     back_inserter(common_elements));
  
    // Print the common elements
    cout << "Common elements: ";
    for (int elem : common_elements)
        cout << elem << " ";
    cout << endl;
  
    return 0;
}


Output

Common elements: 1 2 3 5 7 

Time Complexity: O(MlogM+NlogN) where M is the size of the vector and N is the size of the set./
Space Complexity: O(min(M,N))


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads