English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ vector begin() Usage and Example

C++ Vector (Container)

This function is used to point to the first element of the vector (vector).

begin() vs front()

The begin() function is used to return an iterator pointing to the first element of the vector (vector), while the front() function is used to return a reference to the same element in the vector (vector) container.

Syntax

The syntax of the vector (vector) 'v' is:

iterator it = v.begin();

Parameters

It does not contain any parameters.

Return value

It returns an iterator pointing to the first element of the vector (vector).

Example1

Let's take a simple example.

#include iostream
#include<vector>
using namespace std;
int main()
{
vector<char> v{'a','e','i','o','u'};
vector<char>::iterator itr;
itr = v.begin();
cout<<*itr;
return 0;
}

Output:

a

In this example, an object of the iterator 'itr' is created to access the begin() function, and 'itr' is a vector (vector) type containing character values.

Example2

Let's take another simple example.

#include iostream
#include<vector>
using namespace std;
int main()
{
vector<int> v{1,2,3,4,5};
vector<int>::iterator itr;
itr=v.begin();+2;
cout<<*itr;
return 0;
}

Output:

3

In this example, the begin() function increments2To access the third element of the vector (vector).

C++ Vector (Container)