C++ Standard Library C++ STL Library

C++ <string> - crend() Function



The C++ string::crend function returns the constant reverse iterator (const_reverse_iterator) pointing to the character preceding the first character (reversed past-the-last 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 crend() const noexcept;

Parameters

No parameter is required.

Return Value

A const_reverse_iterator to the reversed past-the-last character of the string.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the string::crend function returns the const_reverse_iterator pointing to the character preceding the first 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.crend();
  crit--;
  cout<<*crit<<" ";
  crit--;
  cout<<*crit<<" ";
  crit--;
  cout<<*crit<<" ";
  return 0;
}

The output of the above code will be:

L e a

Example:

Lets see another example where string::crend function is used with string::crbegin 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