如何删除数组的元素并将剩余元素向下移动。所以,如果我有一个数组,
array[]={1,2,3,4,5}
并且想删除 3 并转移其余的,所以我有,
array[]={1,2,4,5}
我将如何用最少的代码来解决这个问题?
最佳答案
您只需要用数组中的下一个值覆盖您要删除的内容,传播该更改,然后记住新的结束在哪里:
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// delete 3 (index 2)
for (int i = 2; i < 8; ++i)
array[i] = array[i + 1]; // copy next element left
现在你的数组是 {1, 2, 4, 5, 6, 7, 8, 9, 9}
.不能删除多余的 9
因为这是一个静态大小的数组,你只需要忽略它。这可以通过 std::copy
来完成:
std::copy(array + 3, // copy everything starting here
array + 9, // and ending here, not including it,
array + 2) // to this destination
在 C++11 中,使用可以使用 std::move
(算法重载,而不是实用程序重载)。
更一般地说,使用 std::remove
删除匹配值的元素:
// remove *all* 3's, return new ending (remaining elements unspecified)
auto arrayEnd = std::remove(std::begin(array), std::end(array), 3);
更一般地说,有 std::remove_if
.
注意使用std::vector<int>
在这里可能更合适,因为它是一个“真正的”动态分配的调整大小数组。 (从某种意义上说,要求它的 size()
反射(reflect)了已删除的元素。)
关于c++ - 移除一个数组元素并移动剩余的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/879603/