如何在 C++11 中将 std::max 与自定义比较器一起使用?
How to use std::max with a custom comparator in C++11?
我有一个希尔结构的向量,想找到高度最高的一个。这是我的代码:
#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()
返回一个迭代器,*
取消引用以获取实际元素。
相关文章:
- std::设置自定义比较器
- 带自定义比较器的最小优先级队列
- 优先级队列自定义比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- set_intersection使用自定义设置比较器
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 使用迭代器的自定义比较器函数
- Cython中带有自定义比较器的优先级队列
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 定义具有非标准签名的自定义映射比较器
- 为什么在类或结构中传递自定义比较器函数?
- 在priority_queue中使用默认容器但自定义比较器
- 是否有任何统一的方法可以在 c++ 中创建自定义比较器?
- C++ priority_queue与自定义比较器并删除任何项目
- 如何在 C++11 中将 std::max 与自定义比较器一起使用?
- 通过函数指针对类内的 STL SET 使用自定义比较器
- C#二进制编写器自定义
- QList 作为 qt 设计器自定义小部件中的一个属性
- std::sort - 正在传递错误的比较器未定义的行为