C++ vector::crbegin() Function



The C++ vector::crbegin() is a built-in function in C++ that is used to get the last element of a vector using const_reverse_iterator. It returns a const reverse iterator pointing to the last elements (i.e., the reverse beginning) of a vector.The time complexity of the crbegin() function is constant.

The const_reverse_iterator that is returned is an iterator that point to the constant content (vector), and it can be increased or decreased just like an iterator. However, it cannot be used to update or modify the vector content that it points to.

Syntax

Following is the syntax for C++ vector::crbegin() Function −

const_reverse_iterator crbegin() const noexcept;

Parameters

It doesn't contains any kind of parameters.

Example 1

Let's consider the following example, where we are going to use the crbegin() function incremented by 3 to get access to the forth element of the vector.

#include <iostream>  
#include<vector>  
using namespace std;
 
int main(){  
   vector<int> myvector{12,23,34,45,56,67};  
   vector<int>::const_reverse_iterator x=myvector.crbegin()+3;  
   cout<<*x;  
   return 0;  
}

Output

When we compile and run the above program, this will produce the following result −

34

Example 2

In the following example, we are going to use the crbegin() function and accessing the last element in the vector.

#include <iostream>  
#include<vector>  
using namespace std;
  
int main(){  
   vector<string> myvector{"Virat","Yuvraj","Padikkal","MSD"};  
   vector<string>::const_reverse_iterator x=myvector.crbegin();  
   cout<<*x;  
   return 0;
}

Output

On running the above program, it will produce the following result −

MSD

Example 3

Considering the following example, where we are going to use the push_back() for inserting the elements and getting the last element using the crbegin() function.

#include <iostream>
#include <vector>
using namespace std;

int main(){
   vector<int> myvector;
   myvector.push_back(123);
   myvector.push_back(234);
   myvector.push_back(456);
   vector<int>::reverse_iterator x;
   x = myvector.rbegin();
   cout << "The last element is: " << *x << endl;
   return 0;
}

Output

On running the above program, it will produce the following result −

The last element is: 456

Example 4

Looking into the following example, that throws an error when we try to modify the value using the crbegin() function.

#include <iostream>
#include<vector>
using namespace std;
  
int main(){  
   vector<int> myvector{12,23,34,45,56};  
   vector<int>::const_reverse_iterator x=myvector.crbegin();  
   *x=67;  
   cout<<*x;  
   return 0;
} 

Output

On running the above program, it will produce the following result −

Main.cpp:8:5: error
Advertisements