Open In App

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

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

In C++, deques also called double-ended queues are sequence containers that can expand and contract on both ends. The union of two deques means the set of elements that consists of all the elements of the two deques at once. In this article, we will learn how to find the union of two deques in C++.

Example:

Input:
myDeque1 = {10,20,30,40,50,60}
myDeque2 = {10,30,50,40,60,80}

Output: 
union = {10,20,30,40,50,60,80}

Finding Union of Two Deques in C++

To find the union of two std::deque in C++ first, we have to sort both the deques and then use the std::set_union function provided by STL that returns the iterator past the end of the result container where it will store the union of the two deques.

Syntax of std::set_union

set_union (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 Union of Two Deques

The below program demonstrates how we can find the union of two deques in C++.

C++
// C++ Program to illustrate how to find the union of two
// deques
#include <algorithm>
#include <deque>
#include <iostream>
#include <iterator>
using namespace std;

int main()
{
    // Creating and initializing two deques
    deque<int> deque1 = { 1, 2, 3, 4, 5 };
    deque<int> deque2 = { 3, 4, 5, 6, 7 };

    // Printing the elements of the first deque
    cout << "Deque 1: ";
    copy(deque1.begin(), deque1.end(),
         ostream_iterator<int>(cout, " "));
    cout << endl;

    // Printing the elements of the second deque
    cout << "Deque 2: ";
    copy(deque2.begin(), deque2.end(),
         ostream_iterator<int>(cout, " "));
    cout << endl;

    // Creating a third deque to store the union
    deque<int> resultUnion;

    // Sorting both deques to prepare for the union
    // operation
    sort(deque1.begin(), deque1.end());
    sort(deque2.begin(), deque2.end());

    // Merging the two sorted deques to find the union
    set_union(deque1.begin(), deque1.end(), deque2.begin(),
              deque2.end(), back_inserter(resultUnion));

    // Printing the union of the two deques
    cout << "Union of two Deques: ";
    copy(resultUnion.begin(), resultUnion.end(),
         ostream_iterator<int>(cout, " "));
    cout << endl;

    return 0;
}

Output
Deque 1: 1 2 3 4 5 
Deque 2: 3 4 5 6 7 
Union of two Deques: 1 2 3 4 5 6 7 


Time Complexity: O(NlogN + MlogM), here M and N are the size of two deques.
Auxilliary Space: O(N + M)





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads