C++ Standard Library C++ STL Library

C++ <array> - crbegin() Function



The C++ array::crbegin function returns the constant reverse iterator (const_reverse_iterator) pointing to the last element of the array. Please note that, Unlike the array::back function, which returns a direct reference to the last element, it returns the const_reverse_iterator pointing to the same element of the array.

C++ crbegin crend

Note: A const_reverse_iterator is an iterator that points to constant value and iterates in backward direction. Increasing a const_reverse_iterator results into moving to the beginning of the array container and decreasing it results into moving to the end of the array container. Along with this, it cannot be used to modify the contents it points to, even if the array element is not itself constant.

Syntax

const_reverse_iterator crbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A const_reverse_iterator to the reverse beginning of the sequence container.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the array::crbegin function returns the const_reverse_iterator pointing to the last element of the array MyArray.

#include <iostream>
#include <array>
using namespace std;
 
int main (){
  array<string, 3> MyArray{"Alpha","Coding","Skills"};
  array<string, 3>::const_reverse_iterator crit;

  crit = MyArray.crbegin();
  cout<<*crit<<" ";
  crit++;
  cout<<*crit<<" ";
  crit++;
  cout<<*crit<<" ";
  return 0;
}

The output of the above code will be:

Skills Coding Alpha 

Example:

Lets see another example where the array called MyArray contains integer values and array::crbegin function is used with array::crend function to specify a range including all elements of the array container.

#include <iostream>
#include <array>
using namespace std;
 
int main (){
  array<int, 5> MyArray{10, 20, 30, 40, 50};
  array<int, 5>::const_reverse_iterator crit;

  for(crit = MyArray.crbegin(); crit != MyArray.crend(); ++crit)
    cout<<*crit<<" ";

  return 0;
}

The output of the above code will be:

50 40 30 20 10 

❮ C++ <array> Library