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

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

    Another solution in case the i:s are important. This one builds a list that fills in the indexes of which to call doStuff() for. Once again the main point is to avoid the branching and trade it for pipelineable arithmetic costs.

    int buffer[someSafeSize];
    int cnt = 0; // counter to keep track where we are in list.
    for( int i = 0; i < container.size(); i++ ){
       int lDecision = (container[i] == SOMETHING);
       buffer[cnt] = lDecision*i + (1-lDecision)*buffer[cnt];
       cnt += lDecision;
    }
    
    for( int i=0; i

    The "magical" line is the buffer loading line that arithmetically calculates wether to keep the value and stay in position or to count up position and add value. So we trade away a potential branch for some logics and arithmetics and maybe some cache hits. A typical scenario when this would be useful is if doStuff() does a small amount of pipelineable calculations and any branch in between calls could interrupt those pipelines.

    Then just loop over the buffer and run doStuff() until we reach cnt. This time we will have the current i stored in the buffer so we can use it in the call to doStuff() if we would need to.

提交回复
热议问题