Deleting an array element in C

后端 未结 7 1800
自闭症患者
自闭症患者 2021-01-06 14:51

I wrote the following program to delete an array element entered by the user.

#include 
#include 

void main() {
    int j, i,          


        
相关标签:
7条回答
  • 2021-01-06 15:19

    If you don't care about the order of the elements in the array, you can move the last element of the array into the newly formed gap (cunningly reducing the length of the array by one). This can be vastly more efficient than shunting the elements down: in computer science term this makes deleting an element O(1) rather than O(N).

    a[i] = a[--l];
    

    If your i index is looping over the array, you'll want to loop over this element again:

    a[i--] = a[--l];
    

    For example, to remove all elements '3' from an array of length 'l':

    for (i = 0; i < l; ++i) {
        if (a[i] == 3) {
            a[i--] = a[--l];
        }
    }
    

    If you do care about the order of the elements in the array, it's most efficient to use memmove rather than move elements by hand. It's designed to be used where the source and destination memory overlap.

    memmove(a + i, a + i + 1, sizeof(a[0]) * (l - i - 1));
    
    0 讨论(0)
提交回复
热议问题