Open In App

How to Insert Elements from Vectors to a Map in C++?

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

In C++, vectors are the dynamic array that stores data in contiguous memory locations while maps are the data containers that store the key-value pair and are sorted on the basis of the key. In this article, we will learn how to efficiently map elements from vectors to a map in C++.

Example

Input: 
vector<int> keys = {1, 2, 3, 4, 5};
vector<string> values = {"one", "two", "three", "four", "five"};

Output:
Elements in Map:
1: one
2: two
3: three
4: four
5: five

Insert Elements from Vector to a Map in C++

We have one vector that contains keys and the second vector contains values for those keys. To efficiently map these elements from std::vectors to a std::map, we can simply use a loop and iterate over the vectors and keep on inserting key-value pairs in a map.

C++ Program to Convert Values from Vector to Map

The below example demonstrates how we can map values from vector to map.

C++




// C++ program to map elements from vector to map
  
#include <iostream>
#include <map>
#include <vector>
using namespace std;
  
int main()
{
    // Vector of keys and values
    vector<int> keys = { 1, 2, 3, 4 };
    vector<string> values
        = { "one", "two", "three", "four" };
  
    // Map to store key-value pairs
    map<int, string> myMap;
  
    // Populating map from vectors
    for (int i = 0; i < keys.size(); i++) {
        myMap[keys[i]] = values[i];
    }
  
    // Accessing elements in the map and printing them
    cout << "Elements in map:" << endl;
    for (auto it : myMap) {
        cout << it.first << ": " << it.second << endl;
    }
  
    return 0;
}


Output

Elements in map:
1: one
2: two
3: three
4: four

Time Complexity: O(N)
Auxiliary Space: O(N)

Note: For efficient mapping both vectors needs to be of same size and correctly aligned (i.e., each element at index i in the key vector corresponds to the element at the same index in the value vector).

We can also use transform() and std::inserter to map values from a vector to map in C++.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads