2015-10-27 30 views
-3

如何在C++中交換列表中兩個項目(使用數組)的位置。
使用數組。這是我應該完成這項任務的功能。我已經爲數組中的不同元素分配了一個名稱。這裏的變量已經被定義。在數組中交換位置

while (i <= 5) 
    { 
     if (arr[i] == name1){ 
      arr[i] = x; 
      x = tempName; 
      y = x; 
      x = y; 
      cout << y << x << endl; 
     } 
     if (arr[i]== name2){ 
      arr[i] = y; 

      y = tempName; 
      x = y; 
      y = x; 
      cout << y << x << endl; 

     } 

      i = i + 1; 
    } 
    if (arr[i] != name1 || arr[i] != name2) 
    { 
     cout << "You have to pick a name from the line up" << endl; 
    } 
+5

至少假裝傾倒你的功課之前已經做了一些工作! – John3136

+0

我一直堅持這一段時間,但我不能讓我的功能工作。 – NanaGreen346

+3

如果你有代碼在問題中包含它。這是整個問題! – John3136

回答

2

通過你的問題的標題,這裏是如何交換一個數組的元素:

temporary_element = array[i]; 
array[i] = array[j]; 
array[j] = temporary_element; 

,因爲他們在你貼出的問題不是我沒有指定的數據類型。

+0

while(i <= 5)if(arr [i] == name1){ \t arr [i] = X; \t x = tempName; \t y = x; \t x = y; \t cout << y << x << endl; } if(arr [i] == name2){ \t \t \t \t arr [i] = y; \t \t \t \t y = tempName; \t \t \t \t x = y; \t \t \t \t y = x; \t \t \t \t cout << y << x << endl; \t \t \t} \t \t \t \t I = I + 1; \t \t} \t \t if(arr [i]!= name1 || arr [i]!= name2) \t \t { \t \t \t cout <<「您必須從排列中選擇一個名稱」<< endl; \t \t} */ – NanaGreen346

+0

對不起,我不知道如何粘貼代碼,使其以正確的格式顯示。 – NanaGreen346

+0

@妮娜編輯你的問題,並把代碼放在那裏。 – Galik

0

我想你想搜索,然後交換這些元素。 如果您執行了很多操作,請嘗試使用std::set<>std::map<>容器。 搜索在數組中,然後他們在這裏交換是一個簡單的代碼:

int i = 0; 
while (i < N && (name1 != arr[i] || name2 != arr[i])) 
    ++i; 
int id1 = i; 
while (i < N && (name1 != arr[i] || name2 != arr[i]) && arr[id1] != arr[i]) 
    ++i; 
int id2 = i; 
if (id2 < N) 
{ 
    auto tmp = arr[id1]; 
    arr[id1] = arr[id2]; 
    arr[id2] = tmp; 
}