![]() |
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 MapThe below example demonstrates how we can map values from vector to map. C++
Output
Elements in map: 1: one 2: two 3: three 4: four Time Complexity: O(N)
We can also use transform() and std::inserter to map values from a vector to map in C++. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |