C++ Vector cbegin
This function is utilized to reference the initial element of the vector container.
cbegin vs begin
The cbegin method provides a constant iterator, whereas the begin function yields a regular iterator. Objects referenced by the end function are editable, unlike those referenced by the cend function.
Syntax
Consider a vector 'v'. Syntax would be:
const_iterator itr=v.cbegin();
Parameter
It does not contain any parameter.
Return value
It provides the unchanging iterator indicating the initial element of the vector.
Example 1
Let's see a simple example.
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v{1,2,3,4,5};
vector<int>::const_iterator itr=v.cbegin()+2;
*itr=6;
std::cout<<*itr;
return 0;
}
Output:
In this instance, an error occurs when attempting to alter the value using the cbegin function, which is not permissible in this scenario.
Example 2
Let's see a another simple example.
#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> v{"C","C++","cpp",".Net"};
vector<string>::const_iterator citr;
citr=v.cbegin()+1;
cout<<*citr;
return 0;
}
Output:
In this instance, the cbegin method is advanced by 1 in order to retrieve the second element within the vector.