Remove an array element and shift the remaining ones

前端 未结 8 705
灰色年华
灰色年华 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:20

    std::copy does the job as far as moving elements is concerned:

     #include 
    
     std::copy(array+3, array+5, array+2);
    

    Note that the precondition for copy is that the destination must not be in the source range. It's permissible for the ranges to overlap.

    Also, because of the way arrays work in C++, this doesn't "shorten" the array. It just shifts elements around within it. There is no way to change the size of an array, but if you're using a separate integer to track its "size" meaning the size of the part you care about, then you can of course decrement that.

    So, the array you'll end up with will be as if it were initialized with:

    int array[] = {1,2,4,5,5};
    

提交回复
热议问题