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

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

    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

提交回复
热议问题