gpt4 book ai didi

c++ - 从 std::map 中找到具有最大值的元素

转载 作者:IT老高 更新时间:2023-10-28 22:36:45 28 4
gpt4 key购买 nike

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

最佳答案

取自 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 成员,其中包含值(value)。这使用 lambda 表达式,因此您必须使用 C++11 支持进行编译

关于c++ - 从 std::map 中找到具有最大值的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30611709/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com