Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a static two dimensional map<int, int> in C++

I have two dimensional map

map <int, map<int, int>> _map;

The first type of initialization works well:

int i = 1,  j = 2,  k = 3;
map <int, map<int, int>> _map;
_map[i][j] = 100;
_map[i][k] = 200;
std::cout << _map[i][j] << ":" << _map[i][k] << std::endl; 

Thus it prints:

100:200

However, the second initialization fails:

map <int, map<int, int>> _map = {
    {1, {{2, 100}}},
    {1, {{3, 200}}}
  };
  std::cout << _map[i][j] << ":" << _map[i][k] << std::endl;

The second prints:

100:0

I understand that map has "unique keys", on the other hand, we can init like "_map[i][j]".

Could you please explain me how to initialize a static two dimensional map in a right way?

like image 304
DBenson Avatar asked Sep 11 '19 20:09

DBenson


People also ask

How do you initialize a 2D?

On the other hand, to initialize a 2D array, you just need two nested loops. 6) In a two dimensional array like int[][] numbers = new int[3][2], there are three rows and two columns. You can also visualize it like a 3 integer arrays of length 2.


2 Answers

it would be:

map<int, map<int, int>> _map = {
    {1, {{2, 100}, {3, 200}}}
  };

You could also have:

_map[1] = {{2, 100}, {3, 200}};

Your snippet

map <int, map<int, int>> _map = {
    {1, {{2, 100}}},
    {1, {{3, 200}}}
  };

would be "equivalent" (initialization versus insertion) to:

_map.insert({1, {{2, 100}}});
_map.insert({1, {{3, 200}}}); // Fails as key 1 already present.
like image 114
Jarod42 Avatar answered Oct 16 '22 16:10

Jarod42


The two operations are not equivalent. This:

map <int, map<int, int>> _map;
_map[i][j] = 100;
_map[i][k] = 200;

First creates an entry in your map with key i and returns a reference to a value associated with your key - an std::map<int, int>, which then you apply [j] = 100; to. This means that _map has one element - a key-value pair of {i, {j, 100}}.

Then you apply _map[i][k] = 200;, which retrieves a value under i key (the very same std::map<int, int>) and puts a key-value pair of {k, 200} there. Your _map consists now of: {i, {{j, 100}, {k, 200}}}.

Now, why this doesnt work the same:

map <int, map<int, int>> _map = {
    {1, {{2, 100}}},
    {1, {{3, 200}}}
};

that's because here you introduce two key-value pairs. Twice with a key equal 1 with a value equal to separate maps. This is not equivalent. You would need to change your sytax to the following:

map<int, map<int, int>> _map = {
    {1, {{2, 100}, {3, 200}}}
};

This, like the first example, creates one entry (a key-value pair) to your map with a key 1 and a value std::map<int, int> consisting of two entries - {2, 100} and {3, 200}.

like image 44
Fureeish Avatar answered Oct 16 '22 16:10

Fureeish