How to Delete an Element from an Array in C++?
Last Updated :
18 Mar, 2024
In C++, arrays are data structures that allow users to store data of the same type in contiguous memory locations. In this article, we will learn how to delete an element from an array in C++.
Example:
Input:
myarr = {20, 5, 1, 10, 15};
Target: 1
Output:
Array after deletion: 20 5 10 15
Remove an Element from an Array in C++
In C++, arrays are static, which means we cannot change their size once declared. Therefore, technically, we cannot delete an element from an array. However, we can mimic this behavior to delete element from the array in C++ using the below approach:
Approach
- Find the index of the element you want to delete from the array.
- Shift all the elements after that index to the left.
- Update the size of the array after deletion if you are keeping it.
C++ Program to Delete an Element from an Array
The following program illustrates how to delete an element from an array in C++.
C++
// C++ Program to illustrate how to delete an element from
// an array
#include <algorithm>
#include <iostream>
using namespace std;
// Function to delete an element from an array
void deleteElement(int arr[], int& size, int element)
{
int indexToDelete = -1;
// Find the index of the element to delete
int* ptr = find(arr, arr + size, element);
indexToDelete = ptr - arr;
// Print error if the element to delete was not found in
// the array
if (indexToDelete > size - 1) {
cout << "Element not found in the array." << endl;
return;
}
// Shift elements to the left starting from the index to
// be deleted
for (int i = indexToDelete; i < size - 1; ++i) {
arr[i] = arr[i + 1];
}
// Update the size of the array
--size;
}
// driver code
int main()
{
// Initialize an array
int arr[] = { 20, 5, 1, 10, 15 };
// Find the size of the array
int size = sizeof(arr) / sizeof(arr[0]);
// Print the array before deletion
cout << "Array before deletion:";
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
// Declare the element you want to delete from the array
int target = 1;
// Call the deleteElement function to delete the element
deleteElement(arr, size, target);
// Print the updated array after deletion
cout << "Array after deletion:";
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
return 0;
}
OutputArray before deletion:20 5 1 10 15
Array after deletion:20 5 10 15
Time Complexity: O(N), where N is the size of the array.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...