Del*_*gan 61 c++ python loops for-loop break
Python有一个有趣的for语句,允许您指定一个else子句.
在像这样的结构中:
for i in foo:
if bar(i):
break
else:
baz()
Run Code Online (Sandbox Code Playgroud)
该else子句在之后执行for,但仅在for正常终止时(不是由a break)终止.
我想知道C++中是否有相同的东西?我可以用for ... else吗?
Ton*_*roy 34
表达实际逻辑的更简单方法是std::none_of:
if (std::none_of(std::begin(foo), std::end(foo), bar))
baz();
Run Code Online (Sandbox Code Playgroud)
如果接受C++ 17的范围提议,希望这将简化为:
if (std::none_of(foo, bar)) baz();
Run Code Online (Sandbox Code Playgroud)
ify*_*ner 24
如果不介意使用goto也可以通过以下方式完成.这个节省了额外的if检查和更高范围的变量声明.
for(int i = 0; i < foo; i++)
if(bar(i))
goto m_label;
baz();
m_label:
...
Run Code Online (Sandbox Code Playgroud)
hac*_*cks 13
是的,你可以通过以下方式达到同样的效
auto it = std::begin(foo);
for (; it != std::end(foo); ++it)
if(bar(*it))
break;
if(it == std::end(foo))
baz();
Run Code Online (Sandbox Code Playgroud)
Eas*_*ton 11
这是我在C++中的粗略实现:
bool other = true;
for (int i = 0; i > foo; i++) {
if (bar[i] == 7) {
other = false;
break;
}
} if(other)
baz();
Run Code Online (Sandbox Code Playgroud)
Noa*_*ack 10
您可以使用lambda函数:
[&](){
for (auto i : foo) {
if (bar(i)) {
// early return, to skip the "else:" section.
return;
}
}
// foo is exhausted, with no item satisfying bar(). i.e., "else:"
baz();
}();
Run Code Online (Sandbox Code Playgroud)
这应该与Python的"for..else"完全相同,并且与其他解决方案相比具有一些优势:
但是......我会使用笨重的旗帜变量,我自己.
| 归档时间: |
|
| 查看次数: |
14869 次 |
| 最近记录: |