C++ multiset Library - crbegin() Function



Description

The multiset::crbegin() function in C++ STL returns a const reverse iterator that points to the last element in the multiset container. It does not accept any parameters.

Syntax

Following is the syntax of multiset::crbegin in C++11 onwards −

const_reverse_iterator crbegin() const noexcept; //C++11 onwards

Return value

It returns a const reverse iterator. It points to the last element in the multiset container. Since it is constant, you can not modify the elements of the multiset.

Exceptions

It never throws exceptions.

Time complexity

The time complexity of multiset::crbegin() function is constant.

Examples of multiset::crbegin() Function

The following examples demonstrate the usage of multiset::crbegin() function in multiset −

Printing Elements of multiset in Reverse Order

In this example, we have used the crbegin() function with the crend() function to iterate the multiset elements in the reverse order using constant iterators −

#include <iostream>
#include <set>
using namespace std;
int main(){
   multiset<int> nums = {13, 31, 7, 53, 67, 53};
   cout << "Multiset elements in reverse order:\n";
   for (auto it = nums.crbegin(); it != nums.crend(); ++it){
      cout << *it << " ";
   }
   return 0;
}

The output of the above code is given below −

Multiset elements in reverse order:
67 53 53 31 13 7 

Getting Largest Element using crbegin()

To get the largest element in the multiset, the crbegin() function can be used. Since, by default multiset sorts the elements in ascending order, the crbegin() function returns the const reverse iterator pointing at last element, i.e., largest element of the multiset.

#include <iostream>
#include <set>
using namespace std;
int main(){
   multiset<int> nums = {10, 30, 20, 40, 30};
   cout << "Multiset elements:";
   for (auto it = nums.cbegin(); it != nums.cend(); ++it){
      cout << " " << *it;
   }
   cout << "\nLargest element: " << *nums.crbegin() << endl;
   return 0;
}

The output of the above code is given below −

Multiset elements: 10 20 30 30 40
Largest element: 40
multiset.htm
Advertisements