C++ Standard Library C++ STL Library

C++ set - rbegin() Function



The C++ set::rbegin function returns the reverse iterator pointing to the last element of the set. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the set container. Similarly, decreasing a reverse iterator results into moving to the end of the set container.

C++ rbegin rend

Note: Set is an ordered data container which implies all its elements are ordered all the time.

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 sequence container. If the sequence 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 set::rbegin function returns the reverse iterator pointing to the last element of the set MySet.

#include <iostream>
#include <set>
using namespace std;
 
int main (){
  set<string> MySet{"Alpha","Coding","Skills"};
  set<string>::reverse_iterator rit;

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

The output of the above code will be:

Skills Coding Alpha 

Example:

Lets see another example where the set called MySet contains integer values and set::rbegin function is used with set::rend function to specify a range including all elements of the set container. Please note that, Set is an ordered data container.

#include <iostream>
#include <set>
using namespace std;
 
int main (){
  set<int> MySet{55, 25, 128, 5, 72};
  set<int>::reverse_iterator rit;

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

  return 0;
}

The output of the above code will be:

128 72 55 25 5

❮ C++ <set> Library