Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ string::crend function is used to return 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 below example, the string::crend function is used to return the const_reverse_iterator pointing to the character preceding the first character of the string MyString.

#include <iostream>
#include <string>
using namespace std;
 
int main (){
  string MyString = "Learn C++";
  string::const_reverse_iterator crit;

  crit = MyString.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 MyString = "Learn C++";
  string::const_reverse_iterator crit;

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

  return 0;
}

The output of the above code will be:

+ + C   n r a e L  

❮ C++ - String Functions