I have a vector of Hill structs and want to find the one with the heighest height. Here's my code:
#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);
}
But it fails to compile:
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.
How do I fix it?
Aucun commentaire:
Enregistrer un commentaire