交换地图的两个元素

时间:2013-05-20 00:32:36

标签: c++

我有一个map<int, Button*>,其中按钮类有几个属性,特别是一个名为position的整数变量。

如果我想在Button类中交换两个位置,我必须更改密钥,始终为key = Button-&gt;位置,它必须是一张地图。

我想删除地图的两个位置(使用擦除)并重新插入(指示索引):

示例(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;

但似乎没有改变对象。为什么呢?

1 个答案:

答案 0 :(得分:0)

您正在擦除相同的元素(在indexFirst上)两次(查看您的代码)。此外,您似乎将元素插入与最初位置相同的位置:

buttons[posOfSecond] = button2;
buttons[posOfFirst] = button1;

我应该改为:

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

我也会建议更好的策略。不要使用删除和插入,而是在Button类中创建一个mutator方法,它允许您设置position属性的值。然后,您只需获取两个按钮的位置(就像使用访问器方法在代码的第一部分中所做的那样),然后将第一个位置分配给第二个按钮,将第二个位置分配给第一个按钮。你应该在你的Button标题中有这样的东西:

void setPos(int pos);

所以这是一个例子:

map<int, Button*> buttons;

//Find the buttons only once and save their references 
//if you need further information that 
//their storing, instead of constantly searching 
//through the map. This is 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;

你已经完成了。

如果按钮存储的唯一唯一数据是它们的位置,则会出现这种情况,否则您也必须交换其他信息。

这里有很多策略,有不同的交易,但请确保您不仅要考虑它是否有效,还要考虑它是否有效。