vector::begin

Returns a random-access iterator to the first element in the vector.

const_iterator begin() const;
iterator begin();

A random-access iterator that points to the first element, or to the location succeeding an empty vector. You should always compare the value returned with vector::end to ensure it is valid.

If the return value of begin is assigned to a vector::const_iterator, the vector object cannot be modified. If the return value of begin is assigned to an vector::iterator, the vector object can be modified.

// vector_begin.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>
using namespace std;
int main()
{
    vector<int> vec;
    vector<int>::iterator pos;
    vector<int>::const_iterator cpos;

    vec.push_back(1);
    vec.push_back(2);

    cout << "The vector vec contains elements:";
    for (pos = vec.begin(); pos != vec.end(); ++pos)
    {
        cout << " " << *pos;
    }

    cout << endl;

    cout << "The vector vec now contains elements:";
    pos = vec.begin();
    *pos = 20;
    for (; pos != vec.end(); ++pos)
    {
        cout << " " << *pos;
    }
    cout << endl;

    // The following line would be an error because iterator is const
    // *cpos = 200;}
The vector vec contains elements: 1 2
The vector vec now contains elements: 20 2

Header: <vector>

Namespace: std

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft