开发者

Moving positions of strings in an array

int moveToEnd(string a[], int n, int pos);

Eliminate the item at position pos by copying all elements after it one place to the left. Put the item that was thus eliminated into the last position of the array. Return the original position of the item that was moved to the end. Here's an example:

string开发者_运维知识库 actors[5] = { "peter", "lois", "meg", "chris", "stewie" };
int j = moveToEnd(actors, 5, 1);  // returns 1
// actors now contains:  "peter"  "meg"  "chris"  "stewie"  "lois"

This is what I have so far:

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);
}}

it is totally wrong but I am stuck trying to figure out how to move the position to the end and than shift all the other elements to the left.


string save = arr[pos];

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

arr[n - 1] = save;


You don't need your second argument, as you can get the length of the array with a.length

The basic logic is this:

  • store the element at a[pos] in a temp String variable.
  • iterate from a[pos] to a[a.length - 2] storing a[pos + 1] to a[pos]
  • store the temp String to a[a.length - 1]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜