map crbegin() and crend() function in C++ STL
- map::crbegin() is a built-in function in C++ STL which returns a constant reverse iterator referring to the last element in the map container. Since map container contains the element in an ordered way, crbegin() will point to that element that will come last according to the container’s sorting criterion.
Syntax:
map_name.crbegin()
Parameters: The function does not accept any parameter.
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.Return Value: The function returns a constant reverse iterator referring to the last element in the map container.
// C++ program to illustrate// map::crbegin() function#include <bits/stdc++.h>usingnamespacestd;intmain(){// initialize containermap<int,int> mp;// insert elements in random ordermp.insert({ 2, 30 });mp.insert({ 1, 40 });mp.insert({ 3, 60 });mp.insert({ 4, 20 });mp.insert({ 5, 50 });autoite = mp.crbegin();cout <<"The last element is {"<< ite->first<<", "<< ite->second <<"}\n";// prints the elementscout <<"\nThe map in reverse order is: \n";cout <<"KEY\tELEMENT\n";for(autoitr = mp.crbegin(); itr != mp.crend(); ++itr) {cout << itr->first<<'\t'<< itr->second <<'\n';}return0;}Output:The last element is {5, 50} The map in reverse order is: KEY ELEMENT 5 50 4 20 3 60 2 30 1 40 - map::crend() is a built-in function in C++ STL which returns a constant reverse iterator pointing to the theoretical element before the first element in the map. Since map container contains the element in an ordered way, crend() will point to the element theoretically before the first element according to the container’s sorting criterion.
Syntax:
map_name.crend()
Parameters: The function does not accept any parameter.
Return Value: The function returns a constant reverse iterator pointing to the theoretical element before the first element in the map.
// C++ program to illustrate// map::crend() function#include <bits/stdc++.h>usingnamespacestd;intmain(){// initialize containermap<int,int> mp;// insert elements in random ordermp.insert({ 2, 30 });mp.insert({ 1, 40 });mp.insert({ 3, 60 });mp.insert({ 4, 20 });mp.insert({ 5, 50 });// prints the elementscout <<"\nThe map in reverse order is : \n";cout <<"KEY\tELEMENT\n";for(autoitr = mp.crbegin(); itr != mp.crend(); ++itr) {cout << itr->first<<'\t'<< itr->second <<'\n';}return0;}Output:The map in reverse order is : KEY ELEMENT 5 50 4 20 3 60 2 30 1 40

