Compartilhar via


vector::begin

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

const_iterator begin() const;
iterator begin();

Return Value

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.

Remarks

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.

Example

// 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

Requirements

Header: <vector>

Namespace: std

See Also

Reference

vector Class

Standard Template Library