C++ Standard Library C++ STL Library

C++ <string> - rbegin() Function



The C++ string::rbegin function returns the reverse iterator pointing to 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. Please note that, Unlike the string::back function, which returns a direct reference to the last character, it returns the reverse iterator pointing to the same character of the string.

C++ rbegin rend

Syntax

reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A reverse iterator to the reverse beginning 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::rbegin function returns the 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::reverse_iterator rit;

  rit = str.rbegin();
  cout<<*rit<<" ";
  rit++;
  cout<<*rit<<" ";
  rit++;
  cout<<*rit<<" ";
  return 0;
}

The output of the above code will be:

+ + C 

Example:

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