Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ map::rend function is used to return the reverse iterator pointing to the element preceding the first element (reversed past-the-last element) of the map. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the map container. Similarly, decreasing a reverse iterator results into moving to the end of the map container.

C++ rbegin rend

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

Syntax

reverse_iterator rend();
const_reverse_iterator rend() const;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;

Parameters

No parameter is required.

Return Value

A reverse iterator to the reversed past-the-last element 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 below example, the map::rend function is used to return the reverse iterator pointing to the element preceding the first element of the map MyMap.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<int, string> MyMap;
  map<int, string>::reverse_iterator rit;

  MyMap[101] = "John";
  MyMap[102] = "Marry";
  MyMap[103] = "Kim";
  MyMap[104] = "Jo";
  MyMap[105] = "Ramesh";

  rit = MyMap.rend();
  rit--;
  cout<<rit->first<<" "<<rit->second<<"\n";
  rit--;
  cout<<rit->first<<" "<<rit->second<<"\n";
  rit--;
  cout<<rit->first<<" "<<rit->second<<"\n";
  return 0;
}

The output of the above code will be:

101 John
102 Marry
103 Kim

Example:

Lets see another example of map where map::rend function is used with map::rbegin function to specify a range including all elements of the map container.

#include <iostream>
#include <map>
using namespace std;
 
int main (){
  map<string, int> MyMap;
  map<string, int>::reverse_iterator rit;

  MyMap["John"] = 2500;
  MyMap["Jack"] = 2600;
  MyMap["Ella"] = 2000;
  MyMap["Nora"] = 3000;
  MyMap["Adam"] = 3100;

  cout<<"MyMap contains: \n ";
  for(rit = MyMap.rbegin(); rit != MyMap.rend(); ++rit)
    cout<<rit->first<<"  "<<rit->second<<"\n ";

  return 0;
}

The output of the above code will be:

MyMap contains: 
 Nora  3000
 John  2500
 Jack  2600
 Ella  2000
 Adam  3100

❮ C++ <map> Library