# vector::begin function

The vector begin( ) function returns an iterator that points to the first element in the vector.

iterator begin();
const_iterator begin( ) const;

First function
Parameters:
none

Return type
iterator – A read and write iterator which points to the first element in the vector.

Second function
Parameters:
none

Return type
iterator – A read only iterator that points to the first element in the vector.

The iteration of the iterator returned is done in the normal order.

Code example

vector<int> vec={ 12 , 3 , 40 , 90 } ;

vector<int>::iterator vecIt=vec.begin( ) ;

cout<< *vecIt << endl
<< vecIt[0] ;

Output

12
12

You can also use the subscript syntax with the iterator to access the element in the vector as shown above.

Adding a value to the iterator returned by begin( ) is allowed,in such case the position of the element pointed by the iterator is incremented with the value added.

Code example

vector<int>::iterator vecIt1= vec.begin( ) +1 ,///vecIt1 points to second position
vecIt2=vec.begin( ) + 2 ; ///vecIt2 points to third position

cout<< *vecIt1 << endl
<< vecIt2[0] ;

Output

3
40

Now vecIt1 points to second element of the vector so using ‘*‘ operator on vecIt i.e *vecIt1, will access the second element.Even if the subscript value is 0 the second element is still accessed.To access the elements before the position pointed by the iterator we can use a negative index value.This means to access the first element of the vector with vecIt1 we can use a negative index value if subscript syntax is used.However,if the ‘*‘ operator is used we can subtract the iterator with a value according to the required position and access the value.A code example is shown below.

Note the negative index value

Code example

cout<< vecIt1[ 0 ] << endl  //access the second element
<< vecIt1[ -1 ] << endl ;  ///access the first element
<< *(vecIt1 – 1) << endl ;  ///access the first element

cout<< vecIt2[0] << endl  ///access the third element
<< vecIt2[ -1 ] << endl  ///access the second element
<< vecIt2[-2] << endl   ///access the first element
<< *(vecIt2 – 2) ;  ///access the first element

Output

12
3
3
40
12
3
3

The storage layout with the iterator position is shown below.