C++ Array::crbegin() Function



The C++ std::array::crbegin() function is used to return a constant iterator pointing to the last element of the array, allowing traversal in reverse order. Unlike rbegin(, the iterator returned by crbegin() is constant, meaning the elements it points to cannot be modified.

Syntax

Following is the syntax for std::array::crbegin() function.

const_reverse_iterator crbegin() const noexcept;

Parameters

It does not accepts any parameter.

Return Value

This function returns a constant reverse iterator which points to the last element of the array.

Exceptions

This function never throws exception.

Time complexity

Constant i.e. O(1)

Example 1

In the following example, we are going to consider the basic usage of the crbegin() function.

#include 
#include 
using namespace std;
int main(void) {
   array < int, 5 > arr = {10,20,30,40,50};
   for (auto it = arr.crbegin(); it != arr.crend(); ++it)
      cout << * it << " ";
   cout << endl;
   return 0;
}

Output

Output of the above code is as follows −

50 40 30 20 10

Example 2

Consider the following example, where we are going to apply the crbegin() function on the character array.

#include 
#include 
using namespace std;
int main() {
   array < char, 6 > MyArray {'P','R','A','S','U','N'};
   array < char, 6 > ::const_reverse_iterator crit;
   for (crit = MyArray.crbegin(); crit != MyArray.crend(); ++crit)
      cout << * crit << " ";
   return 0;
}

Output

Following is the output of the above code −

N U S A R P 

Example 3

In the following example, we are going to use the crbegin() function on the string array.

#include 
#include 
using namespace std;
int main() {
   array < string, 3 > MyArray {"Tutorials","point","company"};
   array < string, 3 > ::const_reverse_iterator crit;
   for (crit = MyArray.crbegin(); crit != MyArray.crend(); ++crit)
      cout << * crit << " ";
   return 0;
}

Output

If we run the above code it will generate the following output −

company point Tutorials
array.htm
Advertisements