How to Initialize a Map with a Range of Key-Value Pairs in C++?
Last Updated :
29 Feb, 2024
In C++, a map is an associative container that stores elements formed by combining a key and a value. In this article, we will learn how to initialize a map with a range of key-value pairs in C++.
Initializing a Map with a Range of Key-Value Pairs in C++
To initialize a std::map with a range of key-value pairs, we can use the range constructor of std::map. This constructor takes two iterators, the beginning and the end of a range, and copies the elements in that range into the map.
Syntax:
std::map<string, string> New_Map(arr.begin(), arr.end());
where,
- arr is the container where key-value pairs are stored
- New_Map is the map declared
C++ Program to Initialize a Map with a Range of Key-Value Pairs
C++
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
vector<pair<string, int > > arr = { { "apple" , 10 },
{ "banana" , 2 },
{ "cherry" , 3 } };
map<string, int > myMap(arr.begin(), arr.end());
for ( auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
|
Output
apple 10
banana 2
cherry 3
Time Complexity: O(N log N), where N is the number of elements to be inserted.
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...