vector::erase

Removes an element or a range of elements in a vector from specified positions.

iterator erase(
   const_iterator_Where
);
iterator erase(
   const_iterator _First,
   const_iterator_Last
);

Parameters

Parameter

Description

_Where

Position of the element to be removed from the vector.

_First

Position of the first element removed from the vector.

_Last

Position just beyond the last element removed from the vector.

Return Value

An iterator that designates the first element remaining beyond any elements removed, or a pointer to the end of the vector if no such element exists.

Remarks

The erase function does not modify the capacity of the vector, only its size.

Example

// vector_erase.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>

using namespace std;

int main()
{
      
   vector <int> vec;
    vector <int>::iterator pos;

    vec.push_back(10);
    vec.push_back(20);
    vec.push_back(30);
    vec.push_back(40);
    vec.push_back(50);

    cout << "Capacity = " << vec.capacity() << endl;
    cout << "vec =";
    for (pos = vec.begin(); pos != vec.end(); ++pos)
    {
        cout << " " << *pos;
    }        
    cout << endl;

    vec.erase(vec.begin());
    cout << "vec = ";
    for (pos = vec.begin(); pos != vec.end(); ++pos)
    {
        cout << " " << *pos;
    }
    cout << endl;

    vec.erase(vec.begin() + 1, vec.begin() + 3);
    cout << "vec = ";
    for (pos = vec.begin(); pos != vec.end(); ++pos)
    {
        cout << " " << *pos;
    }     
    cout << endl;
    cout << "Capacity after erase calls = " << vec.capacity() << endl;
}
Capacity = 6
vec = 10 20 30 40 50
vec = 20 30 40 50
vec = 20 50
Capacity after erase calls = 6

Requirements

Header: <vector>

Namespace: std

See Also

Reference

vector Class

vector::empty, vector::erase, and vector::push_back

Standard Template Library