0

I have used a reference in this code for map<int ,int> but when I don't use a reference, the map does not get filled recursively. I have already solved this problem but don't know why I need to use a reference when I already provided map<int ,int> as parameter. Can you illustrate in depth?

void util(Node* root,map<int,int> &m, int level) {
    if (!root) return;

    m[level]+=root->data;

    util(root->right,m,level);

    util(root->left,m,level+1);
}

void diagonalSum(Node* root) {
    map<int,int> m;

    util(root,m,0);
    // cout<<m.size();
    for(auto i=m.begin();i!=m.end();i++){
        cout<<i->second<<" ";
    }
    cout<<"\n";
}
faro
  • 50
  • 1
  • 7
  • 1
    If you pass by value, each function call will receive a *copy* of the map. Modifying a copy won't modify the original. Every decent tutorial, book or class should have included that information. – Some programmer dude Jan 06 '20 at 06:23
  • 2
    Start here: [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value) – user4581301 Jan 06 '20 at 06:24
  • You would see the same problem without recursing. – molbdnilo Jan 06 '20 at 10:09

1 Answers1

0

When you don't use a reference, you get a copy of the map when the function is called.

From comment: If you pass by value, each function call will receive a copy of the map. Modifying a copy won't modify the original.

darune
  • 10,480
  • 2
  • 24
  • 62