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


The C++ string::rend function is used to return the reverse iterator pointing to the character preceding the first character (reversed past-the-last character) of the string. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the string. Similarly, decreasing a reverse iterator results into moving to the end of the string.

C++ rbegin rend

Syntax

reverse_iterator rend();
const_reverse_iterator rend() const;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;

Parameters

No parameter is required.

Return Value

A reverse iterator to the reversed past-the-last character of the string. If the string object is constant qualified, the function returns a const_reverse_iterator, else returns an reverse_iterator.

Time Complexity

Constant i.e, Θ(1).

Example:

In the below example, the string::rend function is used to return the 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::reverse_iterator rit;

  rit = MyString.rend();
  rit--;
  cout<<*rit<<" ";
  rit--;
  cout<<*rit<<" ";
  rit--;
  cout<<*rit<<" ";
  return 0;
}

The output of the above code will be:

L e a

Example:

Lets see another example where string::rend function is used with string::rbegin 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::reverse_iterator rit;

  for(rit = MyString.rbegin(); rit != MyString.rend(); ++rit)
    cout<<*rit<<" ";

  return 0;
}

The output of the above code will be:

+ + C   n r a e L 

❮ C++ - <string> Library