Search code examples
c++dynamicdynamic-memory-allocationdelete-operator

c++ delete last element of dynamic array


In c++ I took a dynamic array of n elements

int* a = new int[n];

After shifting left all element of that array, the last element, i.e a[n-1] is useless, and I want to delete it. And after shifting right I need to delete the first element of array, and to have a pointer to second element, i.e I need to make an array with length of n-1. How can I do that?


Solution

  • You need to allocate a new array and copy elements of the original array to the new array.

    Here is a demonstrative program

    #include <iostream>
    #include <utility>
    #include <algorithm>
    
    size_t shift_left( int * &a, size_t n )
    {
        if ( n )
        {
            int *p = new int [n-1];
    
            std::copy( a + 1, a + n, p );
    
            std::swap( a, p );
    
            delete []p;
        }
    
        return n == 0 ? n : n - 1;
    }
    
    size_t shift_right( int * &a, size_t n )
    {
        if ( n )
        {
            int *p = new int [n-1];
    
            std::copy( a, a + n - 1, p );
    
            std::swap( a, p );
    
            delete []p;
        }
    
        return n == 0 ? n : n - 1;
    }
    
    int main() 
    {
        size_t n = 10;      
        int *a = new int[n] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    
        for ( const int *p = a; p != a + n; p++ )
        {
            std::cout << *p << ' ';
        }
    
        std::cout << '\n';
    
        n = shift_left( a, n );
    
        for ( const int *p = a; p != a + n; p++ )
        {
            std::cout << *p << ' ';
        }
    
        std::cout << '\n';
    
        n = shift_right( a, n );
    
        for ( const int *p = a; p != a + n; p++ )
        {
            std::cout << *p << ' ';
        }
    
        std::cout << '\n';
    
        delete []a;
    
        return 0;
    }
    

    Its output is

    0 1 2 3 4 5 6 7 8 9 
    1 2 3 4 5 6 7 8 9 
    1 2 3 4 5 6 7 8 
    

    You can change the functions the following way. When the passed value of n is equal to 1 when just free the original pointer and set it to nullptr.

    For example

    size_t shift_left( int * &a, size_t n )
    {
        if ( n )
        {
            if ( n == 1 )
            {
                delete []a;
                a = nullptr;
            }
            else
            {
                int *p = new int [n-1];
    
                std::copy( a + 1, a + n, p );
    
                std::swap( a, p );
    
                delete []p;
            }               
        }
    
        return n == 0 ? n : n - 1;
    }
    

    As an alternative you can use the standard container std::vector and its member function erase.

    Or you can consider using std::valarray.