How do I write a map literal in C++11? [duplicate]

孤人 提交于 2019-12-06 19:36:50

问题


In Python, I can write a map literal like this:

mymap = {"one" : 1, "two" : 2, "three" : 3}

How can I do the equivalent in C++11?


回答1:


You can actually do this:

std::map<std::string, int> mymap = {{"one", 1}, {"two", 2}, {"three", 3}};

What is actually happening here is that std::map stores an std::pair of the key value types, in this case std::pair<const std::string,int>. This is only possible because of c++11's new uniform initialization syntax which in this case calls a constructor overload of std::pair<const std::string,int>. In this case std::map has a constructor with an std::intializer_list which is responsible for the outside braces.

So unlike python's any class you create can use this syntax to initialize itself as long as you create a constructor that takes an initializer list (or uniform initialization syntax is applicable)




回答2:


You may do this:

std::map<std::string, int> mymap = {{"one", 1}, {"two", 2}, {"three", 3}};


来源:https://stackoverflow.com/questions/20230097/how-do-i-write-a-map-literal-in-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!