从std :: map中查找具有最大值的元素

时间:2015-06-03 05:43:17

标签: c++ std stdmap

我正在尝试从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;
}

为什么它打印第二个元素2 : -1

2 个答案:

答案 0 :(得分:16)

取自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; });

这不是使用std::map::value_comp()(比较键值)而是查看对中的second成员,其中包含值。这使用lambda表达式,因此您必须使用C ++ 11支持进行编译

答案 1 :(得分:2)

this answer

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.

和2&gt; 1. value_comp比较值,而不是值值。因为这就是C ++如何滚动。