是否有与"for ... else"等价的内容? C ++中的Python循环? [英] Is there an equivalent to the "for ... else" Python loop in C++?

查看:68
本文介绍了是否有与"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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆