【问题标题】:find element with max value from std::map [duplicate]从 std::map 中找到具有最大值的元素 [重复]
【发布时间】:2015-08-17 04:02:04
【问题描述】:

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

【问题讨论】:

标签: c++ std stdmap


【解决方案1】:

取自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 支持进行编译

【讨论】:

  • 我同意这个答案。不过,它可以写得更通用一些。如果你知道m 的类型是M,你可以写成[](const M::value_type&amp; p1, const M::value_type&amp; p2)。在 M 中键入更改是稳健的,但这里有不必要的间接性
【解决方案2】:

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 比较 key 值,而不是值值。因为这就是 C++ 的运行方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-02
    • 2016-10-04
    • 2013-11-14
    • 2016-09-02
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多