Blog Archive

Friday, February 28, 2020

C++ : How to Initialize a map in one line using initialzer_list ?

https://thispointer.com/how-to-initialize-a-map-with-stdinitialzer_list/

Syntax:
{
{key1, val1}, 
{key2, val2},
...
{keyN, valN}
}

Hint:
map store the elements internally as a pair, i.e., key-value pair.


Example1: 

Save as: your_file.cpp
#include <vector>
#include <map>
#include <initializer_list>
#include <iostream>
 
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;
}

compile:
g++ -std=c++11 your_file.cpp -o your_program


No comments:

Post a Comment