How to get the last key in a std::map with C++

1 Answer

0 votes
#include <iostream>
#include <map>

int main() {
    // Create a std::map and insert some key-value pairs
    std::map<int, std::string> myMap = {
        {1, "First"},
        {2, "Second"},
        {3, "Third"},
        {4, "Fourth"}
    };

    // Get the last key using rbegin
    int lastKey = myMap.rbegin()->first;

    std::cout << "The last key in the map is: " << lastKey << std::endl;
}



/*
run:

The last key in the map is: 4

*/

 



answered Apr 10, 2025 by avibootz

Related questions

1 answer 79 views
1 answer 47 views
1 answer 101 views
1 answer 82 views
1 answer 78 views
1 answer 73 views
...