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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30611709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:48:09  来源:igfitidea点击:

find element with max value from std::map

c++stdstdmap

提问by aj3423

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

我试图从 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?

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

回答by Levi

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 secondmember in the pair, which contains the value. This uses a lambda expression, so you will have to compile with C++11 support

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

回答by kfsone

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

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_compcompares the keyvalues, not the value values. Because that's how C++ rolls.

并且 2 > 1.value_comp比较键值,而不是值。因为这就是 C++ 的运行方式。