OneBite.Dev - Coding blog in a bite size

Remove Item From Array In C++

Code snippet for how to Remove Item From Array In C++ with sample and detail explanation

Removing an item from an array in C++ might seem daunting if you’re relatively new to this language. But, fear no more, as this simple tutorial will provide you with a detailed and straightforward snippet of code, and subsequently break it down for you to understand its intricacies.

Code snippet for Array Item Removal

Here is a simple code snippet to remove an item from an array:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> arr = {1, 2, 3, 4, 5};

    arr.erase(arr.begin()+1);

    // Print the array
    for(int i = 0; i < arr.size(); i++)
        std::cout << arr[i] << " ";

    return 0;
}

Code Explanation for Array Item Removal

In the first line, we include the <iostream> library that allows us to perform standard input and output operations like cout and cin. <vector> is a library that allows us to use vector functions.

Next, std::vector<int> arr = {1, 2, 3, 4, 5}; sets up a vector (a type of resizable array) with the initial values of 1, 2, 3, 4, 5.

We then use the erase() function to remove the second item from the array. It is done by arr.erase(arr.begin()+1);, as index in C++ starts from 0. So, arr.begin()+1 means the index-1 element is deleted, which is the second item in this case.

The next step involves printing all the elements in the array after deletion of the specified item. The for loop is initiated to iterate over each entry of the array. In each iteration, the cout statement prints the current array item, followed by a space.

The final line return 0; signifies the end of the main function and that it has executed successfully. When you run this code, you will see that the second item, ‘2’, is no longer in the array. The terminal will print: 1 3 4 5.

And that’s how you can remove an item from an array in C++. This technique is extremely useful in various scenarios, like data manipulation, game programming, and algorithm development, to name a few.

c-plus-plus