vector::erase


public member function
iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );

Erase elements

Removes from the vector container either a single element (position) or a range of elements ([first,last)).

This effectively reduces the vector size by the number of elements removed, calling each element's destructor before.

Because vectors keep an array format, erasing on positions other than the vector end also moves all the elements after the segment erased to their new positions, which may not be a method as efficient as erasing in other kinds of sequence containers (deque, list).

This invalidates all iterator and references to elements after position or first.

Parameters

All parameters are of member type iterator, which in vector containers are defined as a random access iterator type.
position
Iterator pointing to a single element to be removed from the vector.
first, last
Iterators specifying a range within the vector to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.


Return value

A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// erasing from vector
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  unsigned int i;
  vector<unsigned int> myvector;

  // set some values (from 1 to 10)
  for (i=1; i<=10; i++) myvector.push_back(i);
  
  // erase the 6th element
  myvector.erase (myvector.begin()+5);

  // erase the first 3 elements:
  myvector.erase (myvector.begin(),myvector.begin()+3);

  cout << "myvector contains:";
  for (i=0; i<myvector.size(); i++)
    cout << " " << myvector[i];
  cout << endl;

  return 0;
}

Output:
myvector contains: 4 5 7 8 9 10


Complexity

Linear on the number of elements erased (destructors) plus the number of elements after the last element deleted (moving).

See also