This tutorial will discuss how to check the last key of map in C++.
The map stores the data in a sorted order of keys, so if somebody wants to check the last key of a map, it means that they’re looking for the largest key in the map.
For example, we have a map of integer and string where keys are of integer type and values are string type. We have initialized this map with certain key-value pairs.
std::map<int, std::string> scoreMap = { {45, "Sanjay"}, {22, "Ritika"}, {35, "Shobhit"}, {29, "John"}, {55, "Mathew"}, {41, "David"}};
Internally, it will store these key-value pairs sorted by the key, which is an integer. So in the last key-value pair of this map, the key will be the maximum. To fetch the last key, we can use the rbegin() function of the map object, it will return an iterator pointing to the last element of the map.
if (!scoreMap.empty()) { // Access the last key int lastKey = scoreMap.rbegin()->first; std::cout << "Last key: " << lastKey << std::endl; }
So the rbegin() function will return an iterator pointing to the last element, and using the iterator, we can fetch the key field using the first member variable.
Like this, in the below example, we will fetch the last key of the map and print it on the console.
Let’s see the complete example,
Frequently Asked:
#include <iostream> #include <map> int main() { std::map<int, std::string> scoreMap = { {45, "Sanjay"}, {22, "Ritika"}, {35, "Shobhit"}, {29, "John"}, {55, "Mathew"}, {41, "David"}}; // Check if the map is non empty if (!scoreMap.empty()) { // Access the last key int lastKey = scoreMap.rbegin()->first; std::cout << "Last key: " << lastKey << std::endl; } else { std::cout << "Map is empty." << std::endl; } return 0; }
Output
Pointers in C/C++ [Full Course]
Last key: 55
Summary
Today, we learned how to check the last key of map in C++.