Create a Deque of Vectors in C++

To create a deque of vectors in C++, we have to create a deque in which each element is an std::vector instance. We can to that by passing the std::vector as the template parameter during the deque declaration.

Syntax to Create a Deque of Vectors in C++.

deque<vector<dataType>> dq_Name;

where,

  • dataType: is the type of data stored in the vectors
  • dq_name: is the name of the deque of vectors.

C++ Program to Create a Deque of Vectors

The below program demonstrates how to create a deque of vectors in C++:

C++
// C++ Program to demonstrate how to create a deque of
// vectors
#include <deque>
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    // Initializing a deque of vectors
    deque<vector<int> > dq;

    // Initializing vectors with few elements
    vector<int> vector1 = { 1, 2, 3 };
    vector<int> vector2 = { 4, 5, 6 };
    vector<int> vector3 = { 7, 8, 9 };

    // Adding vectors to the deque
    dq.push_back(vector1);
    dq.push_back(vector2);
    dq.push_back(vector3);

    // Accessing and printing elements from the deque of
    // vectors
    cout << "Deque of vectors:" << endl;
    int i = 1;
    for (auto& vector : dq) {
        cout << "vector" << i << ": ";
        for (int num : vector) {
            cout << num << " ";
        }
        cout << endl;
        i++;
    }
    return 0;
}

Output
Deque of vectors:
vector1: 1 2 3 
vector2: 4 5 6 
vector3: 7 8 9 

Time Complexity: O(N*M), where N is the number of vectors and M is the average number of elements in each vector.
Space Complexity: O(N*M)




How to Create a Deque of Vectors in C++?

In C++, deques are sequence containers similar to queues but unlike queues, deques allow the insertion and deletion of elements from both ends efficiently. Vectors are dynamic arrays that can resize themselves during the runtime. In this article, we will learn how to create a deque of vectors in C++.

Example:

Input:
vector1 = {1,2,3}
vector2 = {4,5,6}
vector3 = {7,8,9}

Output: 
Deque of Vectors:
vector1 :  1 2 3 
vector2 : 4 5 6 
vector3 : 7 8 9 

Similar Reads

Create a Deque of Vectors in C++

To create a deque of vectors in C++, we have to create a deque in which each element is an std::vector instance. We can to that by passing the std::vector as the template parameter during the deque declaration....