Vector Cbegin Function - C++ Programming Tutorial
C++ Course / STL Vector / Vector Cbegin Function

Vector Cbegin Function

BLUF: Mastering Vector Cbegin Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Vector Cbegin Function

C++ is renowned for its efficiency. Learn how Vector Cbegin Function enables low-level control and high-performance computing in the tutorial below.

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:

Example

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.

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.

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.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience