Home > other >  C Nested map: accessing inner map
C Nested map: accessing inner map

Time:03-27

Why does accessing the inner map in a nested C map only sometimes update the value accessible through the outer map? Specifically, why do cases 1 and 3 in the code below not update the value m[500]["text"]?

My understanding is that indexing into the outer map in all of these cases returns a reference to inner map. So why does only the 2nd case update the outer map correctly? Do cases 1 and 3 get the value of the inner map instead of a reference to it?

#include <iostream>
#include<map>
using namespace std;

int main()
{
    map<int, map<string, int>> m1;
    map<int, map<string, int>> m2;
    map<int, map<string, int>> m3;
    
    auto inner = m1[500];
    inner["text"] = 10;
    
    map<string, int> *ptr = &m2[500];
    (*ptr)["text"] = 20;
    
    map<string, int> inner3 = m3[500];
    inner3["text"] = 30;
    
    cout << "inner  " << inner["text"] << " map " << m1[500]["text"] << endl;
    cout << "ptr    " << (*ptr)["text"] << " map " << m2[500]["text"] << endl;
    cout << "inner3 " << inner3["text"] << " map " << m3[500]["text"] << endl;
    
    return 0;
}

This prints out the following:

inner  10 map 0
ptr    20 map 20
inner3 30 map 0

I would expect all 3 to print non-0 values, but only the 2nd case does.

CodePudding user response:

auto inner = m1[500];
...
map<string, int> inner3 = m3[500];

auto cannot deduce references. Both these statements will create copies of the inner map. Modifying those will just update the copy instead of the original value.

Use references in both cases to achieve the desired effect:

auto& inner = m1[500];
...
map<string, int>& inner3 = m3[500];
  • Related