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


in below code, instead of seeing output

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

i getting output as,

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

please me how resolve problem, going wrong? while debugging found, in first iteration stores

0 -> 1 2 

2nd iteration 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 = 0;     for(i = 0; < 100; i++)     {         ab->x = + 1;         ab->y = + 2;         map.insert(std::pair<int, abc*>(i, ab));     }     map<int, abc*>::iterator it;     for(it = map.begin(); != map.end(); it++)     {         cout << it->first << "->" << it->second->x <<" "<< it->second->y << endl;     }     system("pause");     return 0; } 

ab = new abc(); 

you have 1 abc allocated. , keep modifying in loop , reinserting pointer it. second values of map pointing same single abc.


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

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -