How to Create a Deque of Maps in C++?
Last Updated :
26 Mar, 2024
In C++, the Standard Template Library (STL) provides a container called deque that allows efficient insertion and deletion operations at both ends of the container. A map is an associative container that stores elements in key-value pairs.In this article, we will learn how to create a deque of maps in C++.
Example
Input:
myMap1: {1: "C++", 2: "Python"}
myMap2: {1: "Java", 3: "Javascript"}
Output:
myDeque: [ {1: "C++", 2: "Python"},
{1: "Java", 3: "Javascript"} ]
Create a Deque of Maps in C++
To create a std::deque of std::maps in C++, we have to define the type of the deque element as std::map in the deque declaration as shown in the below syntax:
Syntax to Create a Deque of Maps in C++
deque<map<KeyType, ValueType>> deque_Name;
C++ Program to Create a Deque of Maps
The following program illustrates how to create a deque of maps in C++:
C++
// C++ Program to illustrate how to create a deque of maps
#include <deque>
#include <iostream>
#include <map>
using namespace std;
int main()
{
// Initialize a deque of maps
deque<map<int, string> > dq;
// Initialize maps with few entries
map<int, string> mp1;
mp1[1] = "C++";
mp1[2] = "Java";
map<int, string> mp2;
mp2[1] = "JavaScript";
mp2[2] = "Python";
// Insert the maps to the deque
dq.push_back(mp1);
dq.push_back(mp2);
// Print the deque of maps
cout << "Deque Elements: " << endl;
int i = 1;
for (auto it = dq.begin(); it != dq.end(); ++it) {
cout << "Map" << i << " { ";
for (auto p : *it) {
cout << "{" << p.first << ", " << p.second
<< "} ";
}
i++;
cout << " }" << endl;
}
return 0;
}
OutputDeque Elements:
Map1 { {1, C++} {2, Java} }
Map2 { {1, JavaScript} {2, Python} }
Time Complexity: O(N*M)where N is the number of elements in the map.
Auxiliary Space: O(N*M), where M is the average number of key-value pairs in map.
Share your thoughts in the comments
Please Login to comment...