[英]return statement in lambda expression
I created a lambda expression inside my std::for_each
call. 我在
std::for_each
调用中创建了一个lambda表达式。
In it there is code like this one, but I have building error telling me that 里面有这样的代码,但是我在编译时告诉我
error: expected primary-expression before ‘return’ error: expected `]' before ‘return’
In my head I think that boost-lambda
works mainly with functors, so since return
statement it isn't like that, calling it doesn't work. 在我的脑海中,我认为
boost-lambda
主要与函子一起使用,因此由于return
语句不是那样,因此调用它是行不通的。
Do you know what it is and how to fix it? 您知道它是什么以及如何解决它吗?
Thanks AFG 谢谢AFG
namespace bl = boost::lambda; int a, b; bl::var_type::type a_( bl::var( a ) ); bl::var_type::type b_( bl::var( b ) ); std::for_each( v.begin(), v.end(), ( // ..do stuff here if_( a_ > _b_ ) [ std::cout << _1, return ] ));
You cannot use return
instruction inside lambda expression. 您不能在lambda表达式内使用
return
指令。 Use constructions like if_then_else_return
. 使用类似
if_then_else_return
构造。 They offer syntax that allows producing results. 它们提供允许产生结果的语法。 But in your case
return
is not even required, just throw it away. 但是在您的情况下,甚至不需要
return
,只需将其丢弃即可。
just forget boost-lambda and use the new standard C++ lambda expression instead. 只是忘了boost-lambda,而是使用新的标准C ++ lambda表达式。
@MBZ is right, use C++11 (but not lambda in this case). @MBZ是正确的,请使用C ++ 11(但在这种情况下请不要使用lambda )。
Here is your code with C++11: 这是您使用C ++ 11编写的代码:
int a, b;
std::vector<int> v;
for(int e : v)
{
if(a > b)
std::cout << e;
}
Of course you could do the same with lambdas, but why complicating it like the code below? 当然,您可以对lambda执行相同的操作,但是为什么要像下面的代码一样使它复杂化呢 ?
int a, b;
std::vector<int> v;
std::for_each(v.begin(), v.end(),
[&a,&b](int e)
{
if(a > b)
std::cout << e;
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.