...
/Solution Review: Delete an Element at a Specific Index
Solution Review: Delete an Element at a Specific Index
Let's go over the solution review of the challenge given in the previous lesson.
We'll cover the following...
Solution #
Press the RUN button and see the output!
Press + to interact
#include <iostream>using namespace std;// printArray functionvoid printArray(int * arr, int size) {for (int i = 0; i < size; i++) {cout << arr[i] << " ";}cout << endl;}// delete_element functionvoid delete_element(int *&arr, int size, int index) {// Declare new array dynamicallyint * new_arr = new int[size - 1];// Traverse arrayfor (int i = 0; i < size - 1; i++) {//if (i >= index) {new_arr[i] = arr[i + 1];}else {// Copy elements in new arraynew_arr[i] = arr[i];}}// Free memory pointed out by arrdelete[] arr;// Pointer arr will point to new_arrarr = new_arr;//return arr;}// main functionint main() {// Initialize variablesint size = 5;int index = 3;// Initialize dynamic arrayint * arr = new int[size];// Fill elements in an arrayfor (int i = 0; i < size; i++) {arr[i] = i;}// Call printArray functionprintArray(arr, size);// Call delete_element functiondelete_element(arr, size, index);// Call printArray functionprintArray(arr, size - 1);return 0;}
Explanation
To delete the element at the given index, we copy the elements before ...