Open In App

How to Initialize a Map with a Range of Key-Value Pairs in C++?

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

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




// C++ Program to illustrate how to initialize a map with a
// range of key-value pairs
#include <iostream>
#include <map>
#include <vector>
using namespace std;
  
// Driver Code
int main()
{
    // Creating an vector of pairs
    vector<pair<string, int> > arr = { { "apple", 10 },
                                       { "banana", 2 },
                                       { "cherry", 3 } };
  
    // Initializing a map with a range of key-value pairs
    map<string, int> myMap(arr.begin(), arr.end());
  
    // Displaying the map elements
    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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads