Open In App

How to Find the Last Element in a Map in C++?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a map is a container provided by the STL library that stores data in key-value pairs in an ordered or sorted manner. In this article, we will learn how to find the last key-value pair in a Map in C++.

Example:

Input:
Map: {{1, "C++"}, {2, "Java"}, {3, "Python"}, {4, "JavaScript"}};

Output:
Last Key-Value pair in the Map is : {4, JavaScript}

Find Last Key in a std::map in C++

To find the last key-value pair in a std::map, we can use the std::map::end() function which returns an iterator pointing to the imaginary element after the last element of the map container with a combination of std::prev() to get access to the last key-value pair in the map.

C++ Program to Find the Last Key-Value Pair in a Map

The below example demonstrates how we can find the last key-value pair in a map in C++ STL.

C++




// C++ Program to illustrate how to find the last element in
// a map
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
  
    // Initialize a map with some entries
    map<int, string> myMap = { { 1, "C++" },
                               { 2, "Java" },
                               { 3, "Python" },
                               { 4, "JavaScript" } };
  
    // Find the last key-value pair of the map
    auto lastPair = prev(myMap.end());
  
    // Print the last key-value pair of the map
    cout << "Last Key-Value pair in the Map is : {"
         << lastPair->first << ", " << lastPair->second
         << '}' << endl;
  
    return 0;
}


Output

Last Key-Value pair in the Map is : {4, JavaScript}

Time Complexity: O(1)
Auxiliary Space: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads