2013-05-20 4 views
1

저는 map<int, Button*>입니다. 여기에서 버튼 클래스는 여러 속성, 특히 position이라는 정수 변수를 가지고 있습니다.지도의 두 요소 교환하기

Button 클래스에서 두 위치를 바꾸려면 항상 키 = 단추 - 위치로 키를 변경해야하며 맵이어야합니다.

예 (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[pos1] = button2; 
buttons[pos2] = button1; 

가 나는 또한 더 나은 전략을 추천 할 것입니다 :

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

나는 것은 변경해야합니다. 제거 및 삽입으로 저글링하는 대신 Button 클래스에 mutator 메서드를 만들어 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; 

그리고 당신이 완료됩니다.

버튼이 저장하는 유일한 데이터가 위치 일 경우 true이고, 그렇지 않으면 다른 정보도 바꿔야합니다.

여기에는 다양한 전략이 있지만, 작동하는 경우뿐만 아니라 효율적인 지 여부를 항상 고려해야합니다.

+0

'getPos()'에 의해 반환 된 값이 맵에 저장하는 데 사용 된 키 값과 다른 경우에는 작동하지 않습니다. –

+0

이전에 작성한 내용입니다. –

+0

@CaptainObvlious 예, 코드에 문제가 있음을 알았지 만 사용자가 올바르게 지정하지 않았으므로이 답의 설명을 정리하여 혼란이 없습니다. – lekroif

관련 문제