tags:

views:

75

answers:

3

In the code below, why it is that when I take the address of a map index (which contains a list) and I take the address of the list itself, they both have different values.

See the code below for clarification.

#include <iostream>
#include <list>
#include <map>

using namespace std;

int main()
{
    list<char> listA;   //list of chars

    map<int,list<char> > mapper;    //int to char map

    mapper[1] = listA;

    cout << &(mapper[1]) << endl;
    cout << &listA << endl;
}
+1  A: 

This line will add a copy of the value of the local listA and add it to the map at index 1. You now have two different lists.

mapper[1] = listA;
Charles Bailey
A: 

Because list was copied to the map. Therefore it has same value, but different memory place. This line:

  mapper[1] = listA;

actually called the assignment operator of list, where it copied values into new memory location.

Artem Barger
+2  A: 

You get different addresses because you create a copy of the original list and assing it to the map structure.

Consider using pointers (map< int, list<char>* >).

Olli
Don't like that idea. I would rather use a reference to the copy inside that map.
Martin York