Reputation: 1255
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
Upvotes: 3
Views: 8649
Reputation: 210455
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()
.
Upvotes: 7
Reputation: 171127
I believe the simplest one-liner is:
(*nestedMap)[int][int] = int;
Upvotes: 3
Reputation: 227418
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.
Upvotes: 1
Reputation: 45410
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;
Upvotes: 1