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

前端 未结 14 2055
野的像风
野的像风 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 01:53

    There is no such language construct in C++, but, thanks to the "magic" of the preprocessor, you can make one for yourself. For example, something like this (C++11):

    #include 
    #include 
    using namespace std;
    
    #define FOR_EACH(e, c, b) auto e = c.begin(); for (; e != c.end(); ++e) {b} if (e == c.end()) {}
    
    int main()
    {
        vector v;
        v.push_back(1);
        v.push_back(2);
    
        FOR_EACH(x, v, {
            if (*x == 2) {
                break;
            }        
            cout << "x = " << *x << " ";
        })
        else {
            cout << "else";
        }
    
        return 0;
    }
    

    This should output x = 1 else.

    If you change if (*x == 2) { to if (*x == 3) {, the output should be x = 1 x = 2.

    If you don't like the fact that a variable is added in the current scope, you can change it slightly:

    #define FOR_EACH(e, c, b, otherwise) {auto e = c.begin(); for (; e != c.end(); ++e) {b} if (e == c.end()) {} otherwise }
    

    then use would be:

    FOR_EACH(x, v, {
        if (*x == 2) {
            break;
        }        
        cout << "x = " << *x << " ";
    },
    else {
        cout << "else";
    })
    

    It's not perfect, of course, but, if used with care, will save you some amount of typing and, if used a lot, would become a part of the project's "vocabulary".

提交回复
热议问题