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

C++ Usage and example of vector crbegin()

C++ Vector (Container)

The crbegin() function represents a reverse iterator, returning a const_iterator pointing to the last element of the container.

crbegin() vs rbegin()

The crbegin() function returnsconstant reverse iterator,while the rbegin() function returnsReverse iterator. The element pointed to by the rbegin() function can be modified, but the crbegin() function cannot be modified.

Syntax

Vector (vector) "v". Syntax is:

const_reverse_iterator itr = v.crbegin();

Parameters

It does not contain any parameters.

Return value

It returns a constant reverse iterator that points to the beginning of the container in reverse.

Example1

Let's look at a simple example.

#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v{100,200,300,400};
vector<int>::const_reverse_iterator itr = v.crbegin();
  *itr=500;
cout<<*itr;
return 0;}

Output:

Error

In this example, we try to use the crbegin() function to modify the value, which is not possible in this case.

Example2

Let's look at another simple example.

#include <iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> v{"Mango","banana","strawberry","kiwi"};
vector<string>::const_reverse_iterator itr = v.crbegin();
cout<<*itr;
return 0;
}

Output:

kiwi

In this example, the crbegin() function is used to access the last element of the vector container.

Example3

Let's look at a simple example.

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

Output:

3

In this example, the crbegin() function increments2To access the third element of the vector (vector) and this function accesses all elements from back to front.

C++ Vector (Container)