Open In App

How to Concatenate Two Deques in C++?

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

In C++S, we have a sequence container called deque (an acronym for double-ended queue) that allows the insertions and deletions at both its beginning and its end. In this article, we will learn how to concatenate two deques in C++ STL.

Example:

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

Output:
Concatenated deque is : 10 20 30 40 50 60

Merge Two Deques in C++

We can merge two deques using the std::deque::insert() function that inserts elements from the given range. We have to pass the iterator to the end of the first deque and the iterators to the beginning and the end of the second deque in the function.

Syntax to Concatenate Two Deques in C++

deque1.insert(deque1.end(), deque2.begin(), deque2.end());

Here, deque1 and deque2 are the names of the first deque and second deque respectively.

C++ Program to Concatenate Two Deques

The below example demonstrates how we can use the insert() function to concatenate two deques in C++ STL.

C++
// C++ program to demonstrates how we can use the insert()
// function to concatenate two deques
#include <deque>
#include <iostream>
using namespace std;

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

    // Concatenating the deques
    deque1.insert(deque1.end(), deque2.begin(),
                  deque2.end());

    // Printing the concatenated deque
    cout << "Concatenated deque is : ";
    for (int i : deque1) {
        cout << i << " ";
    }
    cout << endl;

    return 0;
}

Output
Concatenated deque is : 10 20 30 40 50 60 

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




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads