18

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 ?

aj3423
  • 2,003
  • 3
  • 32
  • 70

2 Answers2

22

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

Community
  • 1
  • 1
Levi
  • 1,921
  • 1
  • 14
  • 18
  • 3
    I agree with this answer. It could be written a bit more generic, though. If you know `m` is of type `M`, you might write `[](const M::value_type& p1, const M::value_type& p2)`. It is robust to type changes in `M` but has an unnecessary indirection here – IceFire Jun 01 '17 at 06:58
4

http://www.cplusplus.com/reference/map/map/value_comp/

Returns a comparison object that can be used to compare two elements to get whether
the key of the first one goes before the second.

and 2 > 1. value_comp compares the key values, not the value values. Because that's how C++ rolls.

kfsone
  • 23,617
  • 2
  • 42
  • 74