C++ remove last element from array

To remove the last element from an array in C++, you need to perform the following steps:

  1. Determine the size of the array: Before removing the last element, you need to know the size of the array. This can be done using the sizeof operator or by keeping track of the size manually.

  2. Create a new array: Since arrays have a fixed size in C++, you cannot directly remove an element from an existing array. Instead, you need to create a new array with a size that is one less than the original array.

  3. Copy elements to the new array: Iterate through the original array and copy all elements except the last one to the new array. You can use a for loop or a range-based for loop to achieve this.

  4. Delete the original array: After copying the elements to the new array, you can delete the original array to free up the memory it was occupying. This is done using the delete[] operator.

  5. Assign the new array to the original array: Finally, assign the new array to the original array variable. This step ensures that the original array variable points to the modified array.

Here is an example code snippet that demonstrates these steps:

#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);

    int* newArr = new int[size - 1];

    for (int i = 0; i < size - 1; i++) {
        newArr[i] = arr[i];
    }

    delete[] arr;

    arr = newArr;
    size--;

    for (int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

In this example, we start with an array arr containing elements {1, 2, 3, 4, 5}. We determine the size of the array using the sizeof operator. Then, we create a new array newArr with a size that is one less than the original array. We copy the elements from the original array to the new array using a for loop. After that, we delete the original array to free up the memory and assign the new array to the original array variable. Finally, we print the elements of the modified array.