C++ Standard Library C++ STL Library

C++ <string> - rend() Function



The C++ string::rend function returns 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 example below, the string::rend function returns the 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::reverse_iterator rit;

  rit = str.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 str = "Learn C++";
  string::reverse_iterator rit;

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

  return 0;
}

The output of the above code will be:

+ + C   n r a e L 

❮ C++ <string> Library