Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 789
abw333 Avatar asked Nov 26 '13 23:11

abw333


People also ask

How do you initialize a map with 0?

What exactly do you want to initialize to zero? map's default constructor creates empty map. You may increase map's size only by inserting elements (like m["str1"]=0 or m. insert(std::map<std::string,int>::value_type("str2",0)) ).

How do I change the default value on a map?

To initialize the map with a random default value below is the approach: Approach: Declare a structure(say struct node) with a default value. Initialize Map with key mapped to struct node.


1 Answers

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)

like image 149
aaronman Avatar answered Nov 01 '22 21:11

aaronman