Remove an array element and shift the remaining ones

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

    You can use memmove(), but you have to keep track of the array size yourself:

    size_t array_size = 5;
    int array[5] = {1, 2, 3, 4, 5};
    
    // delete element at index 2
    memmove(array + 2, array + 3, (array_size - 2 - 1) * sizeof(int));
    array_size--;
    

    In C++, though, it would be better to use a std::vector:

    std::vector<int> array;
    // initialize array...
    
    // delete element at index 2
    array.erase(array.begin() + 2);
    
    0 讨论(0)
  • 2020-11-29 01:20

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

     #include <algorithm>
    
     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};
    
    0 讨论(0)
  • 2020-11-29 01:21

    Depending on your requirements, you may want to use stl lists for these types of operations. You can iterate through your list until you find the element, and erase the element. If you can't use lists, then you'll have to shift everything yourself, either by some sort of stl algorithm or manually.

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

    Just so it be noted: If the requirement to preserve the elements order is relaxed it is much more efficient to replace the element being removed with the last element.

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

    You can't achieve what you want with arrays. Use vectors instead, and read about the std::remove algorithm. Something like:

    std::remove(array, array+5, 3)
    

    will work on your array, but it will not shorten it (why -- because it's impossible). With vectors, it'd be something like

    v.erase(std::remove(v.begin(), v.end(), 3), v.end())
    
    0 讨论(0)
  • 2020-11-29 01:31

    If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):

    unsigned int l=0, removed=0;
    
    for( unsigned int i=0; i<count; i++ ) {
        if( array[i] != to_remove )
            array[l++] = array[i];
        else
            removed++;
    }
    
    count -= removed;
    
    0 讨论(0)
提交回复
热议问题