Open In App

How to Find the Intersection of Two Deques in C++?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a deque is a sequence container that allows insertions and deletions at both its ends i.e., the beginning and the end, and the intersection of two deques includes all the common elements in both deques. In this article, we will learn how to find the intersection of two deques in C++.

Example:

Input: 
deque1 = {10, 20, 30, 40};
deque2 = {30, 40, 50, 60};

Output: 
Intersection is : 30 40

Intersection of Two Deques in C++

To find the intersection of two deques in C++, we can use the std::set_intersection function from the <algorithm> library that is used to find the intersection of two sorted ranges. So first, we need to sort the two deques using the std::sort function.

Syntax of std::set_intersection()

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

Here,

  • first1: Iterator to the beginning of the first range.
  • last1: Iterator to the last of the first range.
  • first2: Iterator to the beginning of the second range.
  • last2: Iterator to the last of the second range.
  • result: Iterator to the beginning of the resultant data container.

C++ Program to Find the Intersection of Two Deques

The below example illustrate how we can use the set_intersection() function to find the intersection of two deques in C++ STL.

C++
// C++ program to illustrates how we can use the
// set_intersection() function to find the intersection of
// two deques
#include <algorithm>
#include <deque>
#include <iostream>
#include <iterator>
using namespace std;

int main()
{
    // Creating two deques
    deque<int> deque1 = { 10, 20, 30, 40 };
    deque<int> deque2 = { 30, 40, 50, 60 };

    // Sorting the deques
    sort(deque1.begin(), deque1.end());
    sort(deque2.begin(), deque2.end());

    // Finding the intersection
    deque<int> intersection;
    set_intersection(deque1.begin(), deque1.end(),
                     deque2.begin(), deque2.end(),
                     back_inserter(intersection));

    // Printing the intersection
    cout << "Intersection is : ";
    for (int i : intersection) {
        cout << i << " ";
    }
    cout << endl;

    return 0;
}

Output
Intersection is : 30 40 

Time Complexity: O(N log N), here N is the number of elements in the deque.
Auxiliary Space: O(N)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads