STL Map Data Type

Jun 2, 2014 at 5:23pm
I was having some issues using the map data type from the STL. At first I was just passing the map variable to various functions, add, remove and list. In the add function I had the following code:

1
2
3
4
5
6
7
8
9
10
void addentries(map<string,string> phonebook)
{
    string name, email;
    cout<<"Enter a name:\n";
    cin>>name;
    cout<<"Enter an email:\n";
    cin>>email;
    phonebook[name] = email;
   return;
}

For whatever reason, I could not get the phonebook map to add entries. Then it hit me, do I need to return the phonebook pointer to the caller? The answer was yes, but I'm still not sure why. The following function worked:

1
2
3
4
5
6
7
8
9
10
map<string,string> addentries(map<string,string> phonebook)
{
    string name, email;
    cout<<"Enter a name:\n";
    cin>>name;
    cout<<"Enter an email:\n";
    cin>>email;
    phonebook[name] = email;
   return phonebook;
}


Now I would just like to understand the why. If I'm passing a pointer to a function, all of the work in the function is done on the original memory, nothing is copied?
Jun 2, 2014 at 6:01pm
For whatever reason, I could not get the phonebook map to add entries. Then it hit me, do I need to return the phonebook pointer to the caller? The answer was yes, but I'm still not sure why.

A better solution would've been to pass the map by reference instead of by value.


Now I would just like to understand the why. If I'm passing a pointer to a function, all of the work in the function is done on the original memory, nothing is copied?

There is no pointer passed in either definition of addentries you've shown. In both instances you're passing a copy of the original map.
Jun 2, 2014 at 6:33pm
I just realized when I used the reference last, I didn't change the function declaration, just the definition. So yes, the reference works great!

As for the pointer being passed... I was assuming the map<> data structure was a linked list under the hood, which is a pointer to a head of a list.

Thanks for your help!
Topic archived. No new replies allowed.