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 by avibootz

Related questions

1 answer 37 views
1 answer 44 views
2 answers 115 views
3 answers 90 views
...