Remove A Specific Element From An Array In C++
Code snippet for how to Remove A Specific Element From An Array In C++ with sample and detail explanation
Arrays are fundamental data structures in C++ that allows you to store multiple values of the same type in a single variable. Sometimes, you may need to remove a specific element from an array for various reasons such as to keep the data clean or to optimize the use of memory.
Code snippet to Remove a Specific Element
This code snippet provides a generic way to remove a specific element from an array.
#include <iostream>
int main() {
int arr[]= {10, 20, 30, 40, 50, 60, 30};
int n = sizeof(arr)/sizeof(arr[0]);
int K = 30;
std::cout << "Original array : ";
for (int i=0; i<n; i++)
std::cout << arr[i] << " ";
int i;
for (i=0; i<n; i++)
if (arr[i] == K)
break;
if (i<n)
{
n = n - 1;
for (int j=i; j<n; j++)
arr[j] = arr[j+1];
}
std::cout << "\nArray after removing " << K << " : ";
for (int i=0; i<n; i++)
std::cout << arr[i] << " ";
return 0;
}
Code Explanation for Removing a Specific Element
This code is straightforward and easy to understand. An array, arr
, is created and populated with some integer values.
Firstly, we have to calculate the size of the array, which is done using the formula sizeof(arr)/sizeof(arr[0])
. This formula returns the number of elements present in the array.
A variable, K
, is defined that represents the element that we want to remove from the array.
A loop is initiated with the for
statement, which starts by examining the first element of the array. The loop continues through each element of the array until it either finds the value we’re looking to remove (‘K’) or it has checked all items in the array.
Once the specific element is found, that element is deleted from the array, and the size of the array n
reduces by one. The next elements are shifted to the previous elements using a loop.
After that, the array is printed out again without the removed element K.
This code will remove only the first occurrence of the element. If you want to remove all occurrences, you can keep repeating this loop until the element is no longer found.
Remember that the size of the array is fixed in C++, so technically, we are not reducing the size of the array but just shifting the elements.
This is a simple way to remove a specific element from an array in C++. However, before using arrays in large programs, it’s always good to know that the size of an array in C++ is fixed from the moment of its creation and cannot be altered. If you require resizable arrays, consider using the Standard Library’s data structure called ‘vector’, which can grow and shrink its size as needed.