Python has an interesting for
statement which lets you specify an else
clause.
In a construct like this one:
for i in foo:
if bar(i):
break
else:
baz()
the else
clause is executed after the for
, but only if the for
terminates normally (not by a break
).
I wondered if there was an equivalent in C++? Can I use for ... else
?
Something like:
should do the trick, and it avoids the unstructured
break
.A simpler way to express your actual logic is with
std::none_of
:If the range proposal for C++17 gets accepted, hopefully this will simplify to:
You could use a lambda function for this:
This should behave exactly like Python's "for..else", and it has some advantages over the other solutions:
But... I'd use the clunky flag variable, myself.
It's not only possible in C++, it's possible in C. I'll stick with C++ to make the code comprehensible though:
I doubt I'd let that through a code review, but it works and it's efficient. To my mind it's also clearer than some of the other suggestions.
If doesn't mind using
goto
also can be done in following way. This one saves from extraif
check and higher scope variable declaration.Yes you can achieve the same effect by: