In this article we will discuss how to initialize a map with std::initialzer_list<T>.
Let’s create a map of string as key and int as value and initialize it with initializer_list i.e.
// Initialize a Map of string & int using initializer_list std::map<std::string, int> mapOfMarks = { {"Riti",2}, {"Jack",4} };
Here compiler will create following std::initializer_list<T> object internally,
std::initializer_list<std::pair<const std::string, int> > = { {"Riti",2}, {"Jack",4} };
Here T is a std::pair<const std::string, int> because map store the elements internally as a pair.
Frequently Asked:
Initializing a map of string & vector
// Initialize a Map of string & vector of int using initializer_list std::map<std::string, std::vector<int> > mapOfOccur = { { "Riti", { 3, 4, 5, 6 } }, { "Jack", { 1, 2, 3, 5 } } };
Complete Example is as follows,
Output:
#include <iostream> #include <vector> #include <map> #include <list> int main() { // Initialize a Map of string & int using initializer_list std::map<std::string, int> mapOfMarks = { { "Riti", 2 }, { "Jack", 4 } }; for (auto entry : mapOfMarks) std::cout << entry.first << " :: " << entry.second << std::endl; std::cout << std::endl; // Initialize a Map of string & vector of int using initializer_list std::map<std::string, std::vector<int> > mapOfOccur = { { "Riti", { 3, 4, 5, 6 } }, { "Jack", { 1, 2, 3, 5 } } }; // Iterating over the map for (auto entry : mapOfOccur) { std::cout << entry.first << " :: "; for (int i : entry.second) std::cout << i << " , "; std::cout << std::endl; } return 0; }
Output:
Jack :: 4 Riti :: 2 Jack :: 1 , 2 , 3 , 5 , Riti :: 3 , 4 , 5 , 6 ,
Initializing a member variable map in constructor with std::initializer_list
#include <iostream> #include <vector> #include <map> #include <initializer_list> class Course { std::map<std::string, int> mMapOfMarks; public: Course(std::initializer_list<std::pair<const std::string, int> > marksMap) : mMapOfMarks(marksMap) { } void display() { for (auto entry : mMapOfMarks) std::cout << entry.first << " :: " << entry.second << std::endl; std::cout << std::endl; } }; int main() { // Creating a Course Object and calling the constructor // that accepts a initializer_list Course mathsCourse { { "Riti", 2 }, { "Jack", 4 } }; mathsCourse.display(); return 0; }
Output:
Best Resources to Learn C++:
Jack :: 4 Riti :: 2