find element with max value from std::map

aj3423 picture aj3423 · Jun 3, 2015 · Viewed 35k times · Source

I'm trying to get the element with max value from std::map,

int main() {
    map<int, int> m;
    m[1] = 100;
    m[2] = -1;

    auto x = std::max_element(m.begin(), m.end(), m.value_comp());

    cout << x->first << " : " << x->second << endl;
}

why it prints the second element 2 : -1 ?

Answer

Levi picture Levi · Jun 3, 2015

Taken from here:

auto x = std::max_element(m.begin(), m.end(),
    [](const pair<int, int>& p1, const pair<int, int>& p2) {
        return p1.second < p2.second; });

This, rather than using std::map::value_comp() (which compares the key values) looks at the second member in the pair, which contains the value. This uses a lambda expression, so you will have to compile with C++11 support