Find element with the maximum value in a map in C++
This post will discuss how to find an element with the maximum value in a map in C++.
1. Using std::max_element
The recommended solution is to use the std::max_element to find an element having the maximum value in a map. It returns an iterator pointing to an element with the maximum value in the specified range. It is defined in the <algorithm>
header.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <map> #include <algorithm> int main() { std::map<std::string, int> map = { {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3} }; auto pr = std::max_element(map.begin(), map.end(), [](const auto &x, const auto &y) { return x.second < y.second; }); std::cout << pr->first << std::endl; // four return 0; } |
Here’s a generic version using templates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <map> #include <algorithm> template<typename K, typename V> std::pair<K,V> getMaximumValue(const std::map<K,V> &map) { return *std::max_element(map.begin(), map.end(), [](std::pair<K,V> const &x, std::pair<K,V> const &y) { return x.second < y.second; }); } int main() { std::map<std::string, int> map = { {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3} }; std::pair<std::string, int> pair = getMaximumValue(map); std::cout << pair.first << std::endl; // four return 0; } |
2. Using Loop
Alternatively, we can write a custom function for finding an element with the maximum value in the map. It can be implemented as follows in C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <map> #include <climits> int main() { std::map<std::string, int> map = { {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3} }; std::pair<std::string, int> maxValuePair; int maxValue = INT_MIN; for (const auto &entry: map) { if (maxValue < entry.second) { maxValue = entry.second; maxValuePair = entry; } } std::cout << maxValuePair.first << std::endl; // four return 0; } |
That’s all about finding the element with the maximum value in a map in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)