是否有与"for ... else"等价的内容? C ++中的Python循环? [英] Is there an equivalent to the "for ... else" Python loop in C++?
本文介绍了是否有与"for ... else"等价的内容? C ++中的Python循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python有一个有趣的for
语句,可用于指定else
子句.
Python has an interesting for
statement which lets you specify an else
clause.
在这样的结构中:
for i in foo:
if bar(i):
break
else:
baz()
else
子句在for
之后执行,但前提是for
正常终止(而不是break
终止).
the else
clause is executed after the for
, but only if the for
terminates normally (not by a break
).
我想知道C ++中是否有等效的东西?我可以使用for ... else
吗?
I wondered if there was an equivalent in C++? Can I use for ... else
?
推荐答案
一种表达实际逻辑的简单方法是使用 std::none_of
:
A simpler way to express your actual logic is with std::none_of
:
if (std::none_of(std::begin(foo), std::end(foo), bar))
baz();
如果C ++ 17的范围建议被接受,则希望可以简化为:
If the range proposal for C++17 gets accepted, hopefully this will simplify to:
if (std::none_of(foo, bar)) baz();
这篇关于是否有与"for ... else"等价的内容? C ++中的Python循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文