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

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

    Direct answer: no, you probably can't, or it is compiler-based, at best. BUT here's a hack of a macro that kind of works!

    A few notes:

    I usually program with Qt, so I'm used to having a foreach loop, and never have to deal with iterators directly.

    I tested this with Qt's compiler (v 5.4.2) but it should work. This is gross for several reasons, but generally does what you'd want. I don't condone coding like this, but there's no reason it shouldn't work as long as you're careful with the syntax.

    #include 
    #include 
    
    #define for_else(x, y) __broke__ = false; for(x){y} if (__broke__) {}
    #define __break__ __broke__ = true; break
    
    bool __broke__;  // A global... wah wah.
    
    class Bacon {
      public:
        Bacon(bool eggs);
    
        inline bool Eggs() {return eggs_;}
    
      private:
        bool eggs_;
    };
    
    Bacon::Bacon(bool eggs) {
      eggs_ = eggs;
    }
    
    bool bar(Bacon *bacon) {
      return bacon->Eggs();
    }
    
    void baz() {
      std::cout << "called baz\n";
    }
    
    int main()
    {
      std::vectorbacons;
    
      bacons.push_back(new Bacon(false));
      bacons.push_back(new Bacon(false));
      bacons.push_back(new Bacon(false));
    
      for_else (uint i = 0; i < bacons.size(); i++,
          std::cout << bacons.at(i)->Eggs();
          if (bar(bacons.at(i))) {
            __break__;
          }
      ) else {
        baz();
      }
    
      bacons.push_back(new Bacon(true));
      bacons.push_back(new Bacon(false));
    
      for_else (uint i = 0; i < bacons.size(); i++,
          std::cout << bacons.at(i)->Eggs();
          if (bar(bacons.at(i))) {
            __break__;
          }
      ) else {
        baz();
      }
    
      return EXIT_SUCCESS;
    }
    

提交回复
热议问题