Remove an array element and shift the remaining ones

前端 未结 8 699
灰色年华
灰色年华 2020-11-29 01:09

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} 

and want to del

8条回答
  •  执笔经年
    2020-11-29 01:39

    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
    

    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
    

    In C++11, use can use std::move (the algorithm overload, not the utility overload) instead.

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

    Even more generally, there is std::remove_if.

    Note that the use of std::vector may be more appropriate here, as its a "true" dynamically-allocated resizing array. (In the sense that asking for its size() reflects removed elements.)

提交回复
热议问题