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

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

    There probably isn't a single solution that fits best all problems. In my case a flag variable and a range-based for loop with an auto specifier worked best. Here's an equivalent of the code in question:

    bool none = true;
    for (auto i : foo) {
      if (bar(i)) {
        none = false;
        break;
      }
    }
    if (none) baz();
    

    It is less typing than using iterators. Especially, if you use the for loop to initialize a variable, you may use that instead of the boolean flag.

    Thanks to auto typing it is better than std::none_of, if you want to inline the condition rather than call bar() (and if you are not using C++14).

    I had a situation where both conditions occurred, the code looked something like this:

    for (auto l1 : leaves) {
      for (auto x : vertices) {
        int l2 = -1, y;
        for (auto e : support_edges[x]) {
          if (e.first != l1 && e.second != l1 && e.second != x) {
            std::tie(l2, y) = e;
            break;
          }
        }
        if (l2 == -1) continue;
    
        // Do stuff using vertices l1, l2, x and y
      }
    }
    

    No need for iterators here, because v indicates whether break occurred.

    Using std::none_of would require specifying the type of support_edges[x] elements explicitly in arguments of a lambda expression.

提交回复
热议问题