Declare MAP already passing values in C++ ?

Asked

Viewed 230 times

1

Good guys, I see that with the array I can do this:

int array[]= {5,6,4,2};

My doubt is, in the language C++ i can declare map already passing values ?

Example:

map<string,int> mymap = { "a",1};
  • Use as follows: map<int, char> m = {1, 'a'}, {3, 'b'}, {5, 'c'}, {7, ’d'}};

  • But I want it with string.

  • And that doesn’t even add up.

  • Std::map<Std::string, int> map = { { "String1", 2 }, { "String2", 4 } };

1 answer

3


Actually your example of booting the map got to a {} to be right!

It would only be enough:

map<string,int> mymap = {{"a",1}};
//                      ^       ^

The question is what the first pair of {} represents the map whole and then takes others {} for each initialized element.

So if I wanted to initialize with more elements I could do:

map<string,int> mymap = {{"a",1}, {"b",2}, {"c",3}};

It is worth noting that the support is from C++11

Documentation

  • However, this only works in c++98

  • @Victorocv impossible: https://en.cppreference.com/w/cpp/language/list_initialization

  • @Victorocv Quite the contrary, the support is C++11 for above. If it is lower has no path so direct.

  • You’re wrong Isac, it’s c++98 yes..

  • @Victorocv Can you substantiate your statement ? Is that I have already founded mine. If you look at several of the documentation links that have been passed, such as this see written in "map( std::initializer_list<value_type> ..." numbered (5) version "(Since C++11)".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.