如何在 C++11 中将 std::max 与自定义比较器一起使用?

How to use std::max with a custom comparator in C++11?

本文关键字:比较器 自定义 一起 max C++11 中将 std      更新时间:2023-10-16

我有一个希尔结构的向量,想找到高度最高的一个。这是我的代码:

#include <vector>
#include <algorithm>
#include <assert.h>
struct Hill {
int height;
int changed;
};
int main() {
std::vector<Hill> hills(100);
hills[0].height = 100;
hills[1].height = 150;
auto byHeight = [&](const Hill& a, const Hill& b) {
return a.height < b.height;
};
Hill hill = std::max(hills.begin(), hills.end(), byHeight);
assert(hill.height == 150);
}

但它无法编译:

mcve.cpp:15:10: error: no viable conversion from 'const
std::__1::__wrap_iter<Hill *>' to 'Hill'
Hill hill = std::max(hills.begin(), hills.end(), byHeight);
^      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
mcve.cpp:4:8: note: candidate constructor (the implicit copy constructor) not
viable: no known conversion from 'const std::__1::__wrap_iter<Hill *>' to
'const Hill &' for 1st argument
struct Hill {
^
mcve.cpp:4:8: note: candidate constructor (the implicit move constructor) not
viable: no known conversion from 'const std::__1::__wrap_iter<Hill *>' to
'Hill &&' for 1st argument
struct Hill {
^
In file included from mcve.cpp:1:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/vector:270:
In file included from /Library/Developer/CommandLineTools/usr/include/c++/v1/__bit_reference:15:
/Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:2627:12: error: 
no matching function for call to object of type '(lambda at
mcve.cpp:12:21)'
return __comp(__a, __b) ? __b : __a;
^~~~~~
mcve.cpp:15:22: note: in instantiation of function template specialization
'std::__1::max<std::__1::__wrap_iter<Hill *>, (lambda at mcve.cpp:12:21)>'
requested here
Hill hill = std::max(hills.begin(), hills.end(), byHeight);
^
mcve.cpp:12:21: note: candidate function not viable: no known conversion from
'const std::__1::__wrap_iter<Hill *>' to 'const Hill' for 1st argument
auto byHeight = [&](const Hill& a, const Hill& b) {
^
2 errors generated.

我该如何解决?

更改这两行代码解决了这个问题(感谢@milleniumbug(:

auto hill = std::max_element(hills.begin(), hills.end(), byHeight);
assert(hill->height == 150);

*std::max_element让你得到元素本身。std::max_element返回一个迭代器,让您有机会修改元素。

std::max更改为*std::max_element,它将起作用。随着*.

max_element()返回一个迭代器,*取消引用以获取实际元素。