1

ボタンクラスにmap<int, Button*>はいくつかの属性、特に位置という名前の整数変数があります。

Button クラスの 2 つの位置を入れ替えたい場合は、キーを変更する必要があります。常にキー = ボタン -> 位置になるようにし、マップにする必要があります。

マップの 2 つの位置を削除し (消去を使用)、再挿入 (インデックスを示す) することを考えました。

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

しかし、オブジェクトを変更しないようです。なんで?

4

1 に答える 1

0

同じ要素 (indexFirst) を 2 回消去しています (コードを見てください)。また、最初と同じ位置に要素を挿入しているようです。

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

私は次のように変更する必要があります:

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

また、より良い戦略をお勧めします。削除と挿入をやりくりする代わりに、Button クラスに mutator メソッドを作成します。これにより、position 属性の値を設定できます。次に、両方のボタンの位置を取得し (コードの最初の部分でアクセサー メソッドを使用して行ったように)、最初の位置を 2 番目のボタンに割り当て、2 番目の位置を最初のボタンに割り当てます。ボタンヘッダーに次のようなものが必要です。

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;

これで完了です。

これは、ボタンが保存している一意のデータがその位置だけである場合に当てはまります。それ以外の場合は、他の情報も交換する必要があります。

ここにはさまざまなトレードオフを持つ多くの戦略がありますが、それが機能しているかどうかだけでなく、それが効率的であるかどうかを常に考慮してください。

于 2013-05-20T00:46:13.583 に答える