C++ multiset Library - rbegin() Function



Description

The multiset::rbegin() function in C++ STL returns a reverse iterator that points to the last element in the multiset container. It does not accept any parameters. The returned reverse iterator is used for traversing the multiset container in reverse order.

Syntax

Following are the syntax of multiset::rbegin in various C++ versions −

reverse_iterator rbegin(); //C++98
reverse_iterator rbegin() noexcept; //C++11 onwards

Return value

It returns a reverse iterator pointing to the last element in the multiset container.

Exceptions

It never throws exceptions.

Time complexity

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

Examples of multiset::rbegin() Function

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

Printing Elements of multiset in Reverse Order

In this example, we are using rbegin() iterator to print all the elements present in the multiset container in reverse order. The rbegin() iterator is used to get the last element of the multiset.

#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.rbegin(); it != nums.rend(); ++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 rbegin()

To get the largest element in the multiset, the rbegin() function can be used. Since, by default multiset sorts the elements in ascending order, the rbegin() function returns the reverse iterator pointing to last element in the sorted multiset container, which is the largest element.

#include <iostream>
#include <set>
using namespace std;

int main(){
   multiset<int> nums = {10, 30, 20, 40, 30};
   cout << "Multiset elements:";
   for (auto it = nums.begin(); it != nums.end(); ++it){
      cout << " " << *it;
   }

   cout << "\nLargest element: " << *nums.rbegin() << 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