删除数组元素和移位,其余的 [英] Remove an array element and shift the remaining ones
问题描述
我如何删除数组的元素和移位剩余的元素了。所以,如果我有一个数组,
How do I remove an element of an array and shift the remaining elements down. So, if I have an array,
array[]={1,2,3,4,5}
和要删除3等我倒腾休息,
and want to delete 3 and shift the rest so I have,
array[]={1,2,4,5}
我怎么会去这code量最少的?
How would I go about this in the least amount of code?
推荐答案
您只需要重写你的数组中的下一个值删除的内容,传播这一变化,然后记住其中新到底是:
You just need to overwrite what you're deleting with the next value in the array, propagate that change, and then keep in mind where the new end is:
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 ::复制
:
Now your array is {1, 2, 4, 5, 6, 7, 8, 9, 9}
. You cannot delete the extra 9
since this is a statically-sized array, you just have to ignore it. This can be done with 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 ::移动
(算法超载,不实用过载)来代替。
In C++11, use can use std::move
(the algorithm overload, not the utility overload) instead.
更一般地,使用的std ::删除
删除匹配值的元素:
More generally, use std::remove
to remove elements matching a value:
// 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 ::矢量&lt的; INT&GT;
可能更适合在这里,因为它是一个真正的动态分配调整阵列。 (在这个意义上,要求其尺寸()
反映移除元素。)
Note that the use of std::vector<int>
may be more appropriate here, as its a "true" dynamically-allocated resizing array. (In the sense that asking for its size()
reflects removed elements.)
这篇关于删除数组元素和移位,其余的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!