How to Remove Element From Array in C++

Jinku Hu Mar 12, 2025 C++ C++ Array
  1. Understanding Arrays in C++
  2. Method 1: Shift Elements to Remove an Element
  3. Method 2: Create a New Array
  4. Method 3: Using Standard Template Library (STL)
  5. Use std::to_array and std::remove Functions
  6. Conclusion
  7. FAQ
How to Remove Element From Array in C++

In C++, managing arrays is a fundamental aspect of programming. One common task you may encounter is the need to remove an element from an array. While arrays are fixed in size, there are effective methods to simulate the removal of an element.

This article will guide you through different approaches to achieve this, ensuring that you understand how to manipulate arrays in C++. Whether you’re a beginner or looking to refine your skills, this guide will provide clear examples and explanations to help you master this important concept.

Understanding Arrays in C++

Before diving into the methods for removing elements, it’s essential to grasp what arrays are in C++. An array is a collection of elements, all of the same type, stored in contiguous memory locations. They offer a straightforward way to store multiple values under a single name, but one limitation is their fixed size. Once declared, the size of an array cannot be changed. This is where the challenge of removing an element arises.

When you want to remove an element, you can’t simply delete it like you would in higher-level languages. Instead, you’ll need to shift elements or create a new array. Let’s explore several methods to achieve this.

Method 1: Shift Elements to Remove an Element

One of the most common ways to remove an element from an array in C++ is by shifting the elements. This method involves finding the element you want to remove, then shifting all subsequent elements one position to the left.

Here’s how you can do it:

#include <iostream>
using namespace std;

void removeElement(int arr[], int &n, int element) {
    int i;
    for (i = 0; i < n; i++) {
        if (arr[i] == element) {
            break;
        }
    }
    if (i == n) {
        return; // Element not found
    }
    for (int j = i; j < n - 1; j++) {
        arr[j] = arr[j + 1];
    }
    n--; // Decrease size of array
}

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

    removeElement(arr, n, elementToRemove);

    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}

Output:

1 2 4 5 

In this code, we define a function removeElement that takes an array, its size, and the element to remove. It first searches for the element. If found, it shifts all subsequent elements left by one position and decreases the size of the array. Finally, we print the modified array. This method is efficient for small to medium-sized arrays.

Method 2: Create a New Array

Another effective method to remove an element from an array is to create a new array that contains only the elements you want to keep. This method can be more intuitive and easier to implement, especially for larger arrays.

Here’s an example:

#include <iostream>
using namespace std;

int* removeElement(int arr[], int &n, int element) {
    int* newArr = new int[n - 1];
    int index = 0;

    for (int i = 0; i < n; i++) {
        if (arr[i] != element) {
            newArr[index++] = arr[i];
        }
    }
    n--; // Decrease size of array
    return newArr;
}

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

    int* newArr = removeElement(arr, n, elementToRemove);

    for (int i = 0; i < n; i++) {
        cout << newArr[i] << " ";
    }
    delete[] newArr; // Free allocated memory
    return 0;
}

Output:

1 2 4 5 

In this example, we define a function removeElement that allocates a new array one element smaller than the original. It then copies all elements except the one to be removed into the new array. After adjusting the size, we return the new array. This method is particularly useful when working with larger datasets, as it avoids the need for shifting elements.

Method 3: Using Standard Template Library (STL)

If you’re looking for a more elegant solution, C++’s Standard Template Library (STL) provides powerful tools to manage arrays and collections. Specifically, using a vector can simplify the process of removing elements.

Here’s how to do it with a vector:

#include <iostream>
#include <vector>
using namespace std;

void removeElement(vector<int> &vec, int element) {
    vec.erase(remove(vec.begin(), vec.end(), element), vec.end());
}

int main() {
    vector<int> vec = {1, 2, 3, 4, 5};
    int elementToRemove = 3;

    removeElement(vec, elementToRemove);

    for (int i : vec) {
        cout << i << " ";
    }
    return 0;
}

Output:

1 2 4 5 

In this code, we utilize the vector container from the STL, which automatically manages memory. The remove function shifts elements, and erase removes them from the vector. This method is not only concise but also efficient, making it a popular choice among C++ developers.

Use std::to_array and std::remove Functions

Arrays can be defined as fixed-length or dynamic in C++, and both of them need different methods for element removal. In this example, we consider the built-in C-style fixed arrays, since these are commonly manipulated by the numerical programs for efficiency.

#include <array>
#include <cstring>
#include <iostream>
#include <iterator>

using std::array;
using std::cout;
using std::endl;
using std::remove;

int main() {
  int arr[10] = {1, 1, 1, 2, 2, 6, 7, 8, 9, 10};
  int elem_to_remove = 2;

  cout << "| ";
  for (const auto &item : arr) {
    cout << item << " | ";
  }
  cout << endl;

  auto tmp = std::to_array(arr);
  auto len =
      std::distance(tmp.begin(), (tmp.begin(), tmp.end(), elem_to_remove));
  auto new_arr = new int[len];
  std::memmove(new_arr, tmp.data(), len * sizeof(int));

  cout << "| ";
  for (int i = 0; i < len; ++i) {
    cout << new_arr[i] << " | ";
  }
  cout << endl;

  delete[] new_arr;

  return EXIT_SUCCESS;
}

Output:

| 1 | 1 | 1 | 2 | 2 | 6 | 7 | 8 | 9 | 10 |
| 1 | 1 | 1 | 6 | 7 | 8 | 9 | 10 |

We will declare an array of int and remove the element value of 2, which occurs twice in this array. std::remove is part of the algorithms library and it removes all instances of the given element in the specified range.

Although, at first, we convert the arr object to the std::array container using std::to_array function in order to safely use with std::remove method. The latter algorithm returns the iterator for the new end of the range, which means that the resulting array object still contains 10 elements, and we need to copy them to the new location. Since the original object was a C-style array, we allocate new dynamic memory for the eight-element int array and use the std::memmove function to copy the contents from the array object. Mind though, that we calculated the 8 value using the std::distance function.

Conclusion

Removing an element from an array in C++ can be achieved through various methods, each with its advantages. Whether you choose to shift elements, create a new array, or leverage the power of STL vectors, understanding these techniques will enhance your programming skills. As you work with arrays, consider the context of your application to select the most appropriate method. With practice, you’ll become adept at managing arrays and manipulating data in C++.

FAQ

  1. What is the difference between arrays and vectors in C++?
    Arrays have a fixed size, while vectors can dynamically resize, making them more flexible for managing collections of data.

  2. Can I remove multiple elements from an array in C++?
    Yes, you can modify the methods discussed to accommodate multiple removals, either by adjusting the loop conditions or using STL functions.

  3. Is it possible to remove an element without shifting others?
    In standard arrays, you cannot remove an element without shifting. However, using data structures like linked lists can allow for removal without shifting.

  4. Are there performance considerations when removing elements from arrays?
    Yes, shifting elements can be costly for large arrays. Using STL vectors is often more efficient due to their built-in memory management and resizing capabilities.

  5. How do I handle memory management when using dynamic arrays in C++?
    Always ensure to delete dynamically allocated arrays using delete[] to prevent memory leaks.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

Related Article - C++ Array