C++ Standard Library C++ STL Library

C++ <string> - crbegin() Function



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

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 string and decreasing it results into moving to the end of the string. Along with this, it cannot be used to modify the contents it points to, even if the string character 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 string.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the string::crbegin function returns the const_reverse_iterator pointing to the last character of the string str.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string str = "Learn C++";
  string::const_reverse_iterator crit;

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

The output of the above code will be:

+ + C 

Example:

Lets see another example where string::crbegin function is used with string::crend function to specify a range including all characters of the string.

#include <iostream>
#include <string>

using namespace std;
 
int main (){
  string str = "Learn C++";
  string::const_reverse_iterator crit;

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

  return 0;
}

The output of the above code will be:

+ + C   n r a e L 

❮ C++ <string> Library