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

前端 未结 14 2059
野的像风
野的像风 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:51

    It's not only possible in C++, it's possible in C. I'll stick with C++ to make the code comprehensible though:

    for (i=foo.first(); i != NULL || (baz(),0); i = i.next())
    {
        if bar(i):
            break;
    }
    

    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.

提交回复
热议问题