C++ Standard Library C++ STL Library

C++ map - crend() Function



The C++ map::crend function returns the constant reverse iterator (const_reverse_iterator) pointing to the element preceding the first element (reversed past-the-last element) of the map.

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

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

Syntax

const_reverse_iterator crend() const noexcept;

Parameters

No parameter is required.

Return Value

A const_reverse_iterator to the reversed past-the-last element of the sequence container.

Time Complexity

Constant i.e, Θ(1).

Example:

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

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

  crit = MyMap.crend();
  crit--;
  cout<<crit->first<<" "<<crit->second<<"\n";
  crit--;
  cout<<crit->first<<" "<<crit->second<<"\n";
  crit--;
  cout<<crit->first<<" "<<crit->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::crend function is used with map::crbegin 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>::const_reverse_iterator crit;

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

  cout<<"MyMap contains: \n ";
  for(crit = MyMap.crbegin(); crit != MyMap.crend(); ++crit)
    cout<<crit->first<<"  "<<crit->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