Remove an array element and shift the remaining ones

前端 未结 8 579
灰色年华
灰色年华 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<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.)

    0 讨论(0)
  • 2020-11-29 01:40

    Programming Hub randomly provided a code snippet which in fact does reduce the length of an array

    for (i = position_to_remove; i < length_of_array; ++i) {
            inputarray[i] = inputarray[i + 1];
    }
    

    Not sure if it's behaviour that was added only later. It does the trick though.

    0 讨论(0)
提交回复
热议问题