How can I avoid “for” loops with an “if” condition inside them with C++?

前端 未结 13 1706
滥情空心
滥情空心 2021-01-30 03:31

With almost all code I write, I am often dealing with set reduction problems on collections that ultimately end up with naive \"if\" conditions inside of them. Here\'s a simple

13条回答
  •  面向向阳花
    2021-01-30 04:11

    I am in awe of the complexity of the above solutions. I was going to suggest a simple #define foreach(a,b,c,d) for(a; b; c)if(d) but it has a few obvious deficits, for example, you have to remember to use commas instead of semicolons in your loop, and you can't use the comma operator in a or c.

    #include 
    #include 
    
    using namespace std; 
    
    #define foreach(a,b,c,d) for(a; b; c)if(d)
    
    int main(){
      list a;
    
      for(int i=0; i<10; i++)
        a.push_back(i);
    
      for(auto i=a.begin(); i!=a.end(); i++)
        if((*i)&1)
          cout << *i << ' ';
      cout << endl;
    
      foreach(auto i=a.begin(), i!=a.end(), i++, (*i)&1)
        cout << *i << ' ';
      cout << endl;
    
      return 0;
    }
    

提交回复
热议问题