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

前端 未结 13 1691
滥情空心
滥情空心 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:27

    If DoStuff() would be dependent on i somehow in the future then I'd propose this guaranteed branch-free bit-masking variant.

    unsigned int times = 0;
    const int kSize = sizeof(unsigned int)*8;
    for(int i = 0; i < myCollection.size()/kSize; i++){
      unsigned int mask = 0;
      for (int j = 0; j<kSize; j++){
        mask |= (myCollection[i*kSize+j]==SOMETHING) << j;
      }
      times+=popcount(mask);
    }
    
    for(int i=0;i<times;i++)
       DoStuff();
    

    Where popcount is any function doing a population count ( count number of bits = 1 ). There will be some freedom to put more advanced constraints with i and their neighbors. If that is not needed we can strip the inner loop and remake the outer loop

    for(int i = 0; i < myCollection.size(); i++)
      times += (myCollection[i]==SOMETHING);
    

    followed by a

    for(int i=0;i<times;i++)
       DoStuff();
    
    0 讨论(0)
提交回复
热议问题