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

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

    You could use a lambda function for this:

    [&](){
      for (auto i : foo) {
        if (bar(i)) {
          // early return, to skip the "else:" section.
          return;
        }
      }
      // foo is exhausted, with no item satisfying bar(). i.e., "else:"
      baz();
    }();
    

    This should behave exactly like Python's "for..else", and it has some advantages over the other solutions:

    • It's a true drop-in replacement for "for..else": the "for" section can have side effects (unlike none_of, whose predicate must not modify its argument), and it has access to the outer scope.
    • It's more readable than defining a special macro.
    • It doesn't require any special flag variables.

    But... I'd use the clunky flag variable, myself.

提交回复
热议问题