Rasmi Ranjan Nayak
Rasmi Ranjan Nayak

Reputation: 11948

Could not able to trace how Map is working in C++

In this below code, instead of seeing output as

0 -> 1 2
1 -> 2 3
..
..
99 ->100 101

I am getting output as,

0 -> 100 101
1 -> 100 101
...
99 -> 100 101

Please help me how to resolve this problem, where exactly it is going wrong? While debugging I found, in first iteration it stores

0 -> 1 2

2nd iteration it it updates like,

0 -> 2 3
1 -> 2 3

Why?

class abc{
    public:
        int x, y;
};
std::map<int, abc*> MAP;
int main()
{
    abc *ab;
    ab = new abc();
    int i = 0;
    for(i = 0; i < 100; i++)
    {
        ab->x = i + 1;
        ab->y = i + 2;
        MAP.insert(std::pair<int, abc*>(i, ab));
    }
    map<int, abc*>::iterator it;
    for(it = MAP.begin(); it != MAP.end(); it++)
    {
        cout << it->first << "->" << it->second->x <<" "<< it->second->y << endl;
    }
    system("pause");
    return 0;
}

Upvotes: 0

Views: 144

Answers (3)

stardust
stardust

Reputation: 5988

ab = new abc();

You have only one abc allocated. And you keep modifying it in the loop and reinserting the pointer to it. So all the second values of the map are pointing to the same single abc.


abc *ab;
// ab = new abc();

//
//
for(i = 0; i < 100; i++)
{

    ab = new abc();
    ^^^^^^^^^^^^^^
    ab->x = i + 1;
    ab->y = i + 2;
    MAP.insert(std::pair<int, abc*>(i, ab));
}

Upvotes: 7

taocp
taocp

Reputation: 23634

abc *ab;
ab = new abc();
int i = 0;
for(i = 0; i < 100; i++)
{
    ab->x = i + 1;
    ab->y = i + 2;
    MAP.insert(std::pair<int, abc*>(i, ab));
}

Since you store pointer to class objects into the map. If you do the above, inside your for loop,you keep changing the values of the pointed object, not storing new objects into map.

Try the following:

abc *ab;
int i = 0;
for(i = 0; i < 100; i++)
{

    ab = new abc();
    ab->x = i + 1;
    ab->y = i + 2;
    MAP.insert(std::pair<int, abc*>(i, ab));
}

Upvotes: 1

Vuwox
Vuwox

Reputation: 2359

You are always refering to the same address with :

abc *ab;
ab = new abc();

Upvotes: 1

Related Questions