Skip to main content
1 of 4
samnoon
  • 1.8k
  • 2
  • 16
  • 25

You need to use the Standard Template Library's std::vector::erase function.

Deleting an element from vector (using index)

std::vector<T,Allocator>::erase Usage:

iterator erase (iterator position); // until C++11 
iterator erase( const_iterator pos ); // since C++11 and until C++20 
constexpr iterator erase( const_iterator pos ); // since C++20 

Here there is a single parameter, position which is an iterator pointing to a single element to be removed from the vector. Member types iterator and const_iterator are random access iterator types that point to elements.

How it works

erase function does the following:

  • It removes from the vector either a single element (position)

  • It reduces the container size by the number of elements removed, which are destroyed.

Note: The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

Return value and Complexity

An iterator pointing to the new location of the element that followed the last element was erased by the function call. This is the container end of the operation that erased the last element in the sequence.

Member type iterator is a random access iterator type that points to elements.

Time complexity is linear on the number of elements erased (destructions) plus the number of elements after the last element is deleted (moving).

Example

vec.erase( vector.begin() + 10 ); // Deleting the eleventh element from vector vec 
samnoon
  • 1.8k
  • 2
  • 16
  • 25