对于一个数组,比方说,大小为 5, 我试图在 0 和数组的当前最后一个元素之间找到一个随机位置。
(最后的位置第一次是 4,第二次是 3,以此类推。)
删除该数组位置中的任何元素,将其上方的所有元素向下移动,以便数组中没有空白点。
我试图尽可能节省时间,所以我想避免将所述随机位置设置为 0 或类似的值。
因此,如果我的数组看起来像 int n[] = {1,3,5,7,9};
并且我的随机位置查找器选择了位置 2,我将如何移动 5(position 2) 到最后并将所有内容向下移动,以便我得到的数组看起来像 {1,3,7,9,5}
?
到目前为止我有:
for (int j = 0; j < 5; j++)
{
printf ("before removal:\n");
printarray (array, 5);
int randompos = ( rand() % (5-j) ); //selects random number from 0 to active last pos.
/* ?????? */ = array[randompos]; // What position will hold my random position?
//Also, what goes in place of the 'deleted' element?
insertion_sort (array, 5-j); //sort only the active elements
printf ("after removal:\n");
printarray (array, 5);
}
期望的输出:
before removal:
1,3,5,7,9
(假设随机位置是数组位置 2,存储数字 5)
after removal:
1,3,7,9,5
最佳答案
给定数组 {1,3,5,7,9}
和 pos = 2
,您可以执行以下操作:
int main()
{
int pos = 2;
int arr[] = {1, 3, 5, 7,9};
int length =sizeof(arr)/sizeof(arr[0]);
int val = arr[pos];
for (int i = pos; i < length; i++){
int j = i + 1;
arr[i] = arr[j];
}
arr[length - 1] = val;
return 0;
}
关于c++ - 从数组中删除并移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26368099/