How to Store Vectors as Values in a Map?
Last Updated :
16 Feb, 2024
In C++, vectors are similar to arrays, but unlike arrays, the vectors are dynamic in nature. They can modify their size during the insertion or deletion of elements. On the other hand, Maps are containers that allow the users to store data in the form of key-value pairs. In this article, we will learn how to store vectors as values in maps in C++.
Example:
Input:
myVector1 = {40,50,60}
myVector2 = {10,20,30}
Output:
myMap = { {1: {40,50,60}}, {2: {10,20,30}} }
Store Vectors as Values in a Map in C++
To store vectors as values in maps, we have to first declare the map of vectors as:
map<key_type, vector<type>>
Then we will add the vector with the keys of your preference.
C++ Program to Store Vectors as Values in a Map
C++
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector1 = { 1, 2, 3 };
vector< int > myVector2 = { 10, 20, 30, 40 };
map<string, vector< int > > myMap;
myMap[ "Vector 1" ] = myVector1;
myMap[ "Vector 2" ] = myVector2;
cout << "Vector Values: " ;
for ( const auto & pair : myMap) {
cout << pair.first << ": " ;
for ( int num : pair.second) {
cout << num << " " ;
}
cout << endl;
}
return 0;
}
|
Output
vector1: 1 2 3
vector2: 10 20 30 40
Time Complexity: O(N), where N is the total number of elements in all vectors inserted into the map.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...