Open In App

How to Store Vectors as Values in a Map?

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to demonstrate how to insert vector as values
// in a map
#include <iostream>
#include <map>
#include <vector>
  
using namespace std;
  
int main()
{
    // create vectors
    vector<int> myVector1 = { 1, 2, 3 };
    vector<int> myVector2 = { 10, 20, 30, 40 };
    // Create a map with string keys and vector<int> values
    map<string, vector<int> > myMap;
  
    // Insert multiple vectors into the map
    myMap["Vector 1"] = myVector1;
    myMap["Vector 2"] = myVector2;
  
    cout << "Vector Values: ";
    // Access and print the vectors stored in the map
    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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads