How to Create a Deque of Arrays in C++?
Last Updated :
27 Mar, 2024
In C++, a deque (double-ended queue) is a data structure that allows insertion and deletion at both ends whereas arrays are fixed-size collections of elements. In this article, we will learn how to create a deque of arrays in C++ STL.
Example:
Input:
myArray1 = {1, 4, 8, 9, 11}
myArray2 = {1, 2, 3, 5, 7}
Output:
myDeque: [ {1, 4, 8, 9, 11} {1, 2, 3, 5, 7} ]
Creating a Deque of Arrays in C++
To create a std::deque
of std::array
in C++, we can pass the type of the deque container to be of the type std::array
as a template parameter while declaration.
Syntax to Create a Deque of Arrays in C++
deque<array<dataType, size>> dequeName;
Here,
- dataType denotes the data type of elements stored in the array.
- size denotes the size of the array.
- dequeName is a name of deque of arrays.
Note: We cannot create a deque of Plain Old Arrays as they do not meet the criteria for elements of deque containers which says that the elements should be at least copy constructible and assignable.
C++ Program to Create a Deque of Arrays
The below example demonstrates how we can create a deque of arrays in C++.
C++
// C++ Program to illustrate how to create a deque of array
#include <array>
#include <deque>
#include <iostream>
using namespace std;
int main()
{
// Declaring a deque of arrays
deque<array<int, 3> > myDeque;
// Creating some arrays
array<int, 3> arr1 = { 1, 2, 3 };
array<int, 3> arr2 = { 4, 5, 6 };
array<int, 3> arr3 = { 7, 8, 9 };
// Pushing arrays into the deque
myDeque.push_back(arr1);
myDeque.push_back(arr2);
myDeque.push_back(arr3);
// Checking if the deque is empty
cout << "myDeque: " << endl;
int i = 1;
for (auto& ele : myDeque) {
cout << "Array" << i++ << ": ";
for (auto i : ele) {
cout << i << " ";
}
cout << endl;
}
return 0;
}
OutputmyDeque:
Array1: 1 2 3
Array2: 4 5 6
Array3: 7 8 9
Time Complexity: O(N*M), where N is the number of arrays and M is the average size of each array.
Auxilliary Space: O(N*M)
Share your thoughts in the comments
Please Login to comment...