How to Insert Elements from Vectors to a Map in C++?
Last Updated :
14 Feb, 2024
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++
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
vector< int > keys = { 1, 2, 3, 4 };
vector<string> values
= { "one" , "two" , "three" , "four" };
map< int , string> myMap;
for ( int i = 0; i < keys.size(); i++) {
myMap[keys[i]] = values[i];
}
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++.
Share your thoughts in the comments
Please Login to comment...