C++ map crbegin() FunctionC++ map crbegin() function is used to return a constant reverse iterator referring to the last element in the map container. A constant reverse iterator of map moves in reverse direction and incrementing it until it reaches to the beginning (First element) of the map container and points to the constant element. SyntaxParameterNone Return valueIt returns a constant reverse iterator pointing to the last element of the map. Example 1Let's see a simple example for crbegin() function. Output: mymap in reverse order: [c:300] [b:100] [a:200] In the above example, crbegin() function is used to return a constant reverse iterator pointing to the last element in the mymap map. Because map store the elements in sorted order of keys. Therefore, iterating over a map will result in above order i.e. sorted order of keys. Example 2Let's see a simple example to iterate over the map in reverse order using while loop. Output: ddd :: 11 ccc :: 13 bbb :: 12 aaa :: 10 In the above example, we are using while loop to const_iterate over the map in reverse order and crbegin() function initializing the last element of the map. Because map store the elements in sorted order of keys therefore, iterating over a map will result in above order i.e. sorted order of keys. Example 3Let's see a simple example to get the first element of the reversed map. Output: The first element of the reversed map m1 is: {3, 30} In the above example, crbegin() function returns the first element of the reversed map m1 i.e. {3,30}. Example 4Let's see a simple example to sort and calculate the highest marks. Output: Marks | Roll Number ______________________ 480 | 30 425 | 50 400 | 10 312 | 20 300 | 40 Highest Marks is: 480 Roll Number of Topper is: 30 In the above example, a map marks is implemented where the Roll Number is being stored as value and marks as key. This enables us to take advantage of the auto sorting in maps and lets us to identify the Roll number of the element with the highest marks. Next TopicC++ Map |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India