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

aj3*_*423 15 c++ stdmap std

我正在尝试从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;
}
Run Code Online (Sandbox Code Playgroud)

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

Lev*_*evi 18

取自这里:

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

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

  • 我同意这个答案.不过,它可能会写得更通用一些.如果你知道`m`是`M`类型,你可能会写`[](const M :: value_type&p1,const M :: value_type&p2)`.它对于"M"中的类型变化是健壮的,但在这里有一个不必要的间接 (2认同)

kfs*_*one 5

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.
Run Code Online (Sandbox Code Playgroud)

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