No, there is nothing equivalent to for-else of Python in C++.
There are a few alternatives to transform the function. I'll use a simpler example:
for i in range(a, b):
if condition(i):
break
else:
not_found()
The closest transformation can be achieved using goto
, but you may find that some colleagues are likely to object (because goto is "evil" and scary):
for (int i = a; i < b; i++) {
if (condition(i)) {
goto found;
}
}
not_found();
found:;
Other alternatives, which are also possible in Python are to introduce an additional boolean variable and if
:
bool found = false;
for (int i = a; i < b; i++) {
if (condition(i)) {
found = true;
break;
}
}
if (!found) {
not_found();
}
Or to encapsulate the whole thing within a function, which I think is the most widely accepted alternative both in Python and in C++.
void function()
{
for (int i = a; i < b; i++) {
if (condition(i)) {
return;
}
}
not_found();
}