c++initializationstdinitializerlist

How to initialize an intializer_list?


Some cpp class accept initializer_list as input, for example:

std::map<std::string, int> m{{"CPU", 10}, {"GPU", 15}, {"RAM", 20}};

or

std::map<std::string, int> m={{"CPU", 10}, {"GPU", 15}, {"RAM", 20}};

Is it possible, to define an initializer_list variable, then use it to call the constructor? i.e. something like:

auto il = {{"CPU", 10}, {"GPU", 15}, {"RAM", 20}};

std::map<std::string, int> m = il;

Solution

  • Yes. Example:

    #include <initializer_list>
    #include <map>
    #include <string>
    
    int main() {
        std::initializer_list<std::pair<const std::string, int>> il = {
            {"CPU", 10}, {"GPU", 15}, {"RAM", 20}};
    
        std::map<std::string, int> m = il;
    }