lambda 返回布尔值
我想找到Y坐标较小的点(如果这样的点较多,则找到X最小的点)。 当用 lambda 编写时:
std::min_element(begin, end, [](PointAndAngle& p1, PointAndAngle& p2) {
if (p1.first->y() < p2.first->y())
return true;
else if (p1.first->y() > p2.first->y())
return false;
else
return p1.first->x() < p2.first->x();
}
我得到:
error C3499: a lambda that has been specified to have a void return type cannot return a value
之间有什么区别
// works
std::min_element(begin, end, [](PointAndAngle& p1, PointAndAngle& p2) {
return p1.first->y() < p2.first->y();
}
和
// does not work
std::min_element(begin, end, [](PointAndAngle& p1, PointAndAngle& p2) {
if (p1.first->y() < p2.first->y())
return true;
else
return false;
}
I want to find point, which has the less Y coordinate (if more of such points, find the one with smallest X).
When writing it with lambda:
std::min_element(begin, end, [](PointAndAngle& p1, PointAndAngle& p2) {
if (p1.first->y() < p2.first->y())
return true;
else if (p1.first->y() > p2.first->y())
return false;
else
return p1.first->x() < p2.first->x();
}
I am getting:
error C3499: a lambda that has been specified to have a void return type cannot return a value
what is the difference between:
// works
std::min_element(begin, end, [](PointAndAngle& p1, PointAndAngle& p2) {
return p1.first->y() < p2.first->y();
}
and
// does not work
std::min_element(begin, end, [](PointAndAngle& p1, PointAndAngle& p2) {
if (p1.first->y() < p2.first->y())
return true;
else
return false;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如 Mike 所指出的,如果 lambda 的主体是单个 return 语句,则可以从中推断出返回类型(请参阅 5.1.2/4)(感谢 Mike)。
注意
->布尔
。As Mike noted, if the lambda's body is a single return statement, then the return type is inferred from that (see 5.1.2/4) (thanks Mike).
Note
-> bool
.lambda 的返回类型可以隐式推断,但您需要使用单个
return
语句来实现此目的;这就是为什么你的“工作”lambda 可以工作(返回类型推断为 bool )。sehe 的解决方案显式声明了返回类型,因此它也可以正常工作。
更新:
C++11 标准,§5.1.2/4 规定:
你不工作的 lambda 属于第二类。
The return type of lambdas can be implicitly inferred, but you need to have a single
return
statement to achieve this; that's why your "working" lambda works (return type inferred to bebool
).sehe's solution explicitly declares the return type, so it works fine as well.
Update:
The C++11 standard, §5.1.2/4 states:
Your not-working lambda falls into the second category.