C++ Vector begin
This function is utilized to reference the initial element of the vector.
begin vs front
The begin method is employed to retrieve an iterator that points to the initial element within the vector, whereas the front function is utilized to obtain a reference to that specific element within the vector data structure.
Syntax
Consider a vector 'v' and syntax would be:
iterator it =v.begin();
Parameter
It does not contain any parameter.
Return value
It yields an iterator that references the initial element within the vector.
Example 1
Let's see 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:
In this instance, an iterator object 'itr' is instantiated to invoke the begin method, with 'itr' being of type vector holding character values.
Example 2
Let's see a 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:
In this instance, the begin method is adjusted by 2 to retrieve the third element within the vector.