Is there an equivalent to the “for … else” Python loop in C++?

前端 未结 14 2082
野的像风
野的像风 2021-01-31 01:21

Python has an interesting for statement which lets you specify an else clause.

In a construct like this one:

for i in foo:
  if         


        
14条回答
  •  星月不相逢
    2021-01-31 02:06

    You can use for-else almost like in Python by defining two macros:

    #define BREAK {CONTINUETOELSE = false; break;}
    #define FORWITHELSE(x, y) {bool CONTINUETOELSE = true; x if(!CONTINUETOELSE){} y}
    

    Now you put the for and the else inside the FORWITHELSE macro separated by a comma and use BREAK instead of break. Here is an example:

    FORWITHELSE(
        for(int i = 0; i < foo; i++){
            if(bar(i)){
                BREAK;
            }
        },
        else{
            baz();
        }
    )
    

    There are two things you need to remember: to put a comma before the else and to use BREAK instead of break.

提交回复
热议问题