2

Assume I have a nested map of type pointer. Then is there a single line statement to insert into the nested map,

map<int, map<int, int> >* nestedMap;

Currently I am doing this in 2 steps. First creating innermap and then insert into outer map as below,

nestedMap->insert(make_pair(int, map<int, int>)(int, innermap));

If the map is not pointer type, then i can insert easily like this,

nestedMap[int][int] = int;

Is there any simple ways for inserting into nested map of type pointer ?

thanks Prabu

flies
  • 2,017
  • 2
  • 24
  • 37
Prabu
  • 1,225
  • 4
  • 18
  • 26
  • I think this is enough easy - just a single line on code. For better reading - I suggest you to make a class Map , then method `bool insert(T, T)` (something like a wrapper of this ugly line) – Don Angelo Annoni Nov 19 '12 at 08:28

4 Answers4

7

map::operator[] automatically creates the key/value pair if it doesn't exist.
(That's why it's not const!) So you don't need to create the inner map manually.

If you want to avoid creating the pair automatically, then use map::find() or map::at().

user541686
  • 205,094
  • 128
  • 528
  • 886
3

I believe the simplest one-liner is:

(*nestedMap)[int][int] = int;
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

access the operator[] via ->:

nestedMap->operator[](5)[6] = 7;

This is analogous to

nestedMap[5][6] = 7;

if nestedMap is not a pointer.

Note that in neither case do you have to explicitly insert a map.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

If i understand your question properly, you can actually use reference instead of pointer. You are not having issue with nested map, instead your outter map.

See below code, is what you want?

map<int, map<int, int> >* nestedMap  = new map<int, map<int, int> >;   
map<int, map<int, int> > &nestedMapAlais = *nestedMap;
nestedMapAlais[1][2] = 3;
billz
  • 44,644
  • 9
  • 83
  • 100
  • So far I thought we can't insert via (*nestedMap)[][], so only i raised this question. Now it clears. Thanks for your information – Prabu Nov 19 '12 at 09:18