Tips and Tricks

Правка en1, от Nourhan_Abo-Heba, 2025-11-07 15:57:43

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_element iterates through all pairs.
  • The lambda compares elements based on their second value.
  • The iterator it points 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;

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en11 Английский Nourhan_Abo-Heba 2026-02-06 03:56:06 215
en10 Английский Nourhan_Abo-Heba 2026-02-05 20:58:56 182
en9 Английский Nourhan_Abo-Heba 2026-02-04 01:08:10 274
en8 Английский Nourhan_Abo-Heba 2026-02-02 02:16:25 1714 Reverted to en6
en7 Английский Nourhan_Abo-Heba 2026-02-02 02:13:08 1714
en6 Английский Nourhan_Abo-Heba 2026-02-02 02:07:01 568
en5 Английский Nourhan_Abo-Heba 2026-02-02 02:05:19 1383
en4 Английский Nourhan_Abo-Heba 2026-02-02 00:39:24 337
en3 Английский Nourhan_Abo-Heba 2026-02-02 00:38:11 2780
en2 Английский Nourhan_Abo-Heba 2026-02-02 00:30:37 1056
en1 Английский Nourhan_Abo-Heba 2025-11-07 15:57:43 784 Initial revision (published)