Find the Max Value in a std::map
Since std::map is sorted by keys, not values, you can use std::max_element to find the pair with the largest value:
auto it = max_element(
m.begin(), m.end(),
[](const auto &a, const auto &b) {
return a.second < b.second;
}
);
cout << "Max value: " << it->second << " (Key: " << it->first << ")" << endl;
Explanation:
std::max_elementiterates through all pairs.- The lambda compares elements based on their
secondvalue. - The iterator
itpoints to the pair with the maximum value.
Bonus
If you want the maximum key instead, you can write:
auto last = m.rbegin();
cout << last->first << " " << last->second;




