2011-05-01 34 views
0
int moveToEnd(string a[], int n, int pos); 

通過複製左邊一個位置後的所有元素來消除位置pos處的項目。將這樣被淘汰的項目放入數組的最後位置。返回移動到最後的項目的原始位置。這裏有一個例子:在陣列中移動字符串的位置

string actors[5] = { "peter", "lois", "meg", "chris", "stewie" }; 
int j = moveToEnd(actors, 5, 1); // returns 1 
// actors now contains: "peter" "meg" "chris" "stewie" "lois" 

這是我到目前爲止有:

int moveToEnd(string a[], int n, int pos) 
{int i = 0; 
int initial; 
int initial2; 
int initial3; 
for (i=0; i<n; i++) 
    {if (i<pos) 
     initial=i-1; 
    if (i>pos) 
     initial2=i-1; 
    else 
     pos + (n-pos); 
}} 

,這是完全錯誤的,但我堅持試圖找出如何將位置移動到終點,比將所有其他元素轉移到左側。

回答

1
string save = arr[pos]; 

for (int i = pos; i < n - 1; i++) 
    arr[i] = arr[i + 1]; 

arr[n - 1] = save; 
+0

謝謝!最後我會返回什麼,因爲它給我一個消息,說沒有價值返回。我在想這個叫save的新位置需要,但這是一個字符串,而不是int – Brandyn 2011-05-01 16:21:32

+0

@Brandyn - 'arr'是輸入數組。在你的情況下,它被稱爲'a'。 – 2011-05-01 16:24:28

+0

慢慢來到某個地方。它現在編譯,但一旦它這樣做,它會提供一個錯誤,說該項目無法正常工作。這是我格式化它。 – Brandyn 2011-05-01 16:28:05

1

你不需要你的第二個參數,你可以得到數組的長度a.length

的基本邏輯是這樣的:

  • 儲存在一個a[pos]元素temp String變量。從a[pos]
  • 迭代到a[a.length - 2]存儲a[pos + 1]a[pos]
  • 店臨時Stringa[a.length - 1]