【发布时间】:2018-06-21 13:32:02
【问题描述】:
我创建了一个名为elements_n 的数组,其中包含0 到N-1 的元素,其中N 为2。下面的数字是名为elements_n 的数组的元素:
0 1
我有另一个名为 Arr 的数组,其中包含以下元素:
0 1 3 1 2 4
如果数组Arr 的前3 个元素中的任何一个等于elements_n 的第一个元素0,我想从名为Arr 的数组中删除该元素。然后我对数组Arr 的下三个元素重复相同的过程。因此,为了更好地解释自己,我将使用以下示例:
比较数组Arr的前3个元素0、1、3与elements_n的第一个元素0。因为Arr[0] == elements_n[0]。我从数组Arr 中删除Arr[0]。
比较数组Arr 的下三个元素(1、2、4)与elements_n 的第二个元素(1)。因为Arr[3] == elements_n[1]。我从数组Arr 中删除Arr[3]。所以应该留在数组Arr中的元素是:
1 3 2 4
当我使用 C 编程自己实现它时,最终结果如下:
1 3 3 2 2 4
而不是:
1 3 2 4
这是我实现的代码:
#include <stdio.h>
#include <stdlib.h>
#define N 2
int main() {
unsigned *elements_n = malloc(N * sizeof(unsigned));
for (int i = 0; i < N; i++) {
elements_n[i] = i; //Created an array which has the elements 0 to N-1
}
printf("\n");
unsigned Arr[6] = { 0, 1, 3, 1, 2, 4 };
unsigned position_indices[2] = { 3, 3 }; //Moving every 3 elements in the Arr array.
int count = 0;
int index = 0;
unsigned *ptr_Arr = &Arr[0];
do {
for (int i = 0; i < position_indices[count]; i++) {
if (ptr_Arr[i] == elements_n[count]) {
index = i + 1; //Index of the Arr element that has the same value as the element in the array elements_n
for (int j = index - 1; j < position_indices[count] - 1; j++) {
ptr_Arr[j] = ptr_Arr[j + 1];
}
}
}
printf("\n");
ptr_Arr += position_indices[count] - 1;
count++;
} while (count < 2);
for (int i = 0; i < 6; i++) {
printf("%d\t", Arr[i]);
}
printf("\n");
free(elements_n);
return 0;
}
【问题讨论】:
-
@Gerhardh 我必须这样做,因为代码是另一个项目的一部分,其中每 3 个元素进行一次比较。抱歉,不清楚。
-
“从数组中删除元素”是什么意思?数组具有固定数量的元素;您不能向其中添加元素或从中删除元素。您可以做的是将有用元素的数量存储在某处并操作数组中有用的部分。
-
position_indices在您的代码中扮演什么角色。 -
for (int i = 0; i < 6; i++)你总是打印所有 6 个元素。您需要跟踪删除了多少元素。 -
将其视为复制整个数组但跳过您不想要的条目。
标签: c arrays if-statement indices array-difference