0

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;
}
4

3 回答 3

7
ab = new abc();

你只abc分配了一个。你不断地在循环中修改它并重新插入指向它的指针。所以secondmap 的所有值都指向同一个 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));
}
于 2013-04-18T17:37:14.627 回答
1

您总是引用相同的地址:

abc *ab;
ab = new abc();
于 2013-04-18T17:39:19.447 回答
1
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));
}

由于您将指向类对象的指针存储到映射中。如果您执行上述操作,则在您的 for 循环中,您会不断更改指向对象的值,而不是将新对象存储到 map 中。

尝试以下操作:

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));
}
于 2013-04-18T17:40:54.957 回答