Xeo*_*Xeo 13 c++ lambda break nested-loops c++11
就像我们都知道的那样,break从外部循环中嵌套循环并不容易,没有:
虽然,你必须承认,所有这些都有点笨拙.特别是函数版本缺少,因为缺少调用循环的上下文,因为您需要将循环中所需的所有内容作为参数传递.
另外,第二个对于每个嵌套循环都会变得更糟.
所以,我个人仍然认为该goto版本是最干净的.
现在,考虑所有C++ 0x和东西,第三个选项带给我这个想法利用lambda表达式:
#include <iostream>
bool CheckCondition(){
return true;
}
bool CheckOtherCondition(){
return false;
}
int main(){
[&]{while(CheckCondition()){
for(;;){
if(!CheckOtherCondition())
return;
// do stuff...
}
// do stuff...
}}();
std::cout << "yep, broke out of it\n";
}
Run Code Online (Sandbox Code Playgroud)
这允许return第三种选择提供的简单的语义美,同时不会遇到上下文问题并且(几乎)像goto版本一样干净.它比任何上述选项都更短(以字符为单位).
现在,我已经学会了在找到语言的美妙(ab)使用后保持喜悦,因为几乎总有一些缺点.这个有什么吗?或者甚至有更好的方法来解决这个问题?
Joh*_*itb 16
请不要在我管理的项目中这样做.在我看来,这是对lambdas的尴尬滥用.
使用goto其中一个goto是有用的.
我认为完全正确。虽然我更喜欢为我的代码分配名称,使代码更加自我记录,即
int main(){
auto DoThatOneThing = [&]{while(CheckCondition()){
for(;;){
if(!CheckOtherCondition())
return;
// do stuff...
}
// do stuff...
}};
DoThatOneThing();
std::cout << "yep, broke out of it\n";
}
Run Code Online (Sandbox Code Playgroud)