我有一个map<int, Button*>
其中按钮类有几个属性,特别是一个名为位置的整数变量。交换地图的两个元素
如果我想在Button类中交换两个位置,我必须改变这个键,始终是key = Button-> position,它必须是一个映射。
我认为(使用擦除)并重新插入删除的地图的两个位置中的(指示索引):
实施例(indexFirst和indexSecond是已知的):
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;
但似乎没有改变对象。为什么?
但你甚至在哪里做交换?看着你的代码,我没有看到。 Button1位于indexFirst或posOfFirst的位置,而button2位于indexSecond或posOfSecond的位置,这在代码中没有改变。 – Amadeus