How to remove vector elements by index in C++

Removing elements from a particular position in an array is essential in many programming applications and in this article, we will learn about different ways of performing this on the C++ dynamic array (vector).

Using the STL functions:

The vector class has a member function called erase(). One of an overload of this function takes an iterator an element and removes that element from the sequence.

The syntax for the function is:

erase (iterator to the element to be erased):

Moreover, the vector has random access iterators, thus the iterator to the required index can be obtained using simple iterator arithmetic.

The following code illustrates the point:

#include <iostream>
#include <vector>
int main()
{

  std::vector<int> a={1,2,3,4,5,6,7};
  int index=3;

  auto it=a.begin();  //iterator to the first element
  it+=index; //iterator to the element to be removed
  a.erase(it);
  std::cout << "the new vector is\n";
  for (int x : a)
  {
    std::cout << x << " ";
  }
}

 

Output:
the new vector is
1 2 3 5 6 7 


Using user-defined function:

Sometimes, it’s easy to forget the existence of the erase function. Removing a single element can be easily performed with some loping statements and the pop_back() function of the vector container.

The algorithm to do this is basically swapping the element to be removed with its next element until it reaches the end position. In the last position, it can be easily removed in constant time.

This algorithm performance is almost identical to the STL version of erase and can be used for removing single elements.

The following code illustrates the point:

#include <iostream>
#include <vector>
template<typename T>
void remove_at(std::vector<T> &a,int index) // function template to work with all type of vectors
{
  for (int i = index; i < a.size() - 1; i++)
  {
    std::swap(a[i], a[i + 1]); //swaping elements till the end
  }
  a.pop_back();
}
int main()
{
  std::vector<int> a={1,2,3,4,5,6,7};
  int index=3;
  remove_at(a, index);
  std::cout << "the new vector is\n";
  for (int x : a)
  {
    std::cout<<x<<" ";
  }
}

 

The output of the code is the same as in the previous section.

Leave a Reply

Your email address will not be published. Required fields are marked *