How to Find the Last Element in a Map in C++?
Last Updated :
05 Mar, 2024
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , string> myMap = { { 1, "C++" },
{ 2, "Java" },
{ 3, "Python" },
{ 4, "JavaScript" } };
auto lastPair = prev(myMap.end());
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)
Share your thoughts in the comments
Please Login to comment...