gpt4 book ai didi

c++ - 移动数组中字符串的位置

转载 作者:行者123 更新时间:2023-11-28 03:49:59 24 4
gpt4 key购买 nike

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"

这是我目前所拥有的:

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

这是完全错误的,但我一直在试图弄清楚如何将位置移到最后,而不是将所有其他元素移到左边。

最佳答案

string save = arr[pos];

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

arr[n - 1] = save;

关于c++ - 移动数组中字符串的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5849564/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com