C++ Standard Library C++ STL Library

C++ set - crbegin() Function



The C++ set::crbegin function returns the constant reverse iterator (const_reverse_iterator) pointing to the last element of the set.

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 set container and decreasing it results into moving to the end of the set container. Along with this, it cannot be used to modify the contents it points to, even if the set element is not itself constant.

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

Syntax

const_reverse_iterator crbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A const_reverse_iterator to the reverse beginning of the sequence container.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the set::crbegin function returns the const_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>::const_reverse_iterator crit;

  crit = MySet.crbegin();
  cout<<*crit<<" ";
  crit++;
  cout<<*crit<<" ";
  crit++;
  cout<<*crit<<" ";
  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::crbegin function is used with set::crend 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>::const_reverse_iterator crit;

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

  return 0;
}

The output of the above code will be:

128 72 55 25 5  

❮ C++ <set> Library

5