2013-05-20 53 views
1

我有一个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; 

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

+0

但你甚至在哪里做交换?看着你的代码,我没有看到。 Button1位于indexFirst或posOfFirst的位置,而button2位于indexSecond或posOfSecond的位置,这在代码中没有改变。 – Amadeus

回答

0

您正在擦除相同的元素(在indexFirst处)两次(查看您的代码)。此外,它看来,你是在相同的位置插入元素作为其最初:

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

我的事情应该改为:

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

我还建议更好的策略。除了使用删除和插入操作外,还可以在Button类中创建一个增变器方法,该方法允许您设置position属性的值。然后,您只需获取这两个按钮的位置(如使用访问器方法在代码的第一部分中所做的那样),然后将第一个位置分配给第二个按钮,将第二个位置分配给第一个按钮。你应该有这样的事情在您的按钮标题:

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; 

和你做。

如果按钮存储的唯一唯一数据是它们的位置,这将是真实的,否则您必须交换其他信息。

这里有很多策略,有不同的交易方式,但要确保你不仅要考虑它是否工作,而且要考虑它是否有效。

+0

如果'getPos()'返回的值与用于将其存储在映射中的键值不同,那么这将不起作用。 –

+0

这是你编辑之前;) –

+0

@CaptainObvlious是的,我看到了代码的问题,但你没有正确指定它,我会清理这个答案的评论,所以没有混乱。 – lekroif