DBenson
DBenson

Reputation: 387

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?

Upvotes: 5

Views: 1542

Answers (2)

Fureeish
Fureeish

Reputation: 13434

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}.

Upvotes: 2

Jarod42
Jarod42

Reputation: 218138

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.

Upvotes: 5

Related Questions