c++ - Swap two elements of map -


i have map<int, button*> wherein button class has several attributes, in particular integer variable named position.

if want swap 2 positions in button class, have change key, key = button-> position , has map.

i thought of deleting 2 positions of map (using erase) , reinsert (indicating index):

example (indexfirst , indexsecond known):

map<int, button*> buttons;  int posoffirst = buttons.find(indexfirst)->second->getpos(); int posofsecond = buttons.find(indexsecond)->second->getpos();  button* button1 = buttons.find(indexfirst)->second; button* button2 = buttons.find(indexsecond)->second;  buttons.erase(indexfirst); buttons.erase(indexfirst);  buttons[posofsecond] = button2; buttons[posoffirst] = button1; 

but appears not change object. why?

you erasing same element (at indexfirst) twice (look @ code). appears inserting elements @ same positions initially:

buttons[posofsecond] = button2; buttons[posoffirst] = button1; 

i thing should changed :

buttons[pos1] = button2; buttons[pos2] = button1; 

i recommend better strategy. instead of juggling removals , insertions, make mutator method in button class, allows set value of position attribute. acquire position of both buttons (as did in first part of code using accessor methods) , assign first position second button , second position first button. should have in button header:

void setpos(int pos); 

so here example:

map<int, button*> buttons;  //find buttons once , save references  //if need further information  //their storing, instead of searching  //through map. more efficient button* button1 = buttons.find(indexfirst)->second; button* button2 = buttons.find(indexsecond)->second;  int pos1 = button1->getpos(); int pos2 = button2->getpos();  button1->setpos(pos2); button2->setpos(pos1);  buttons[pos2] = button1; buttons[pos1] = button2; 

and done.

this true if unique data buttons storing position, otherwise have swap other information too.

there lot of strategies here, different trade ofs, make sure take account not if working, whether efficient.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -