Skipping in Range-based for based on 'index'?

后端 未结 7 1317
一向
一向 2021-01-02 01:10

Is there a way to access the iterator (suppose there\'s no loop index..?) in a C++11 range-based for loop?

Often we need to do something special with the fi

7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 01:59

    Often we need to do something special with the first element of a container and iterate over the remaining elements.

    I am surprised to see that nobody has proposed this solution so far:

      auto it = std::begin(container);
    
      // do your special stuff here with the first element
    
      ++it;
    
      for (auto end=std::end(container); it!=end; ++it) {
    
          // Note that there is no branch inside the loop!
    
          // iterate over the rest of the container
      }
    

    It has the big advantage that the branch is moved out of the loop. It makes the loop much simpler and perhaps the compiler can also optimize it better.

    If you insist on the range-based for loop, maybe the simplest way to do it is this (there are other, uglier ways):

    std::size_t index = 0;
    
    for (auto& elem : container) {
    
      // skip the first element
      if (index++ == 0) {
         continue;
      }
    
      // iterate over the rest of the container
    }
    

    However, I would seriously move the branch out of the loop if all you need is to skip the first element.

提交回复
热议问题