How to increment an iterator by 2?

前端 未结 8 1696
眼角桃花
眼角桃花 2020-12-04 16:16

Can anybody tell me how to increment the iterator by 2?

iter++ is available - do I have to do iter+2? How can I achieve this?

相关标签:
8条回答
  • 2020-12-04 16:55

    std::advance( iter, 2 );

    This method will work for iterators that are not random-access iterators but it can still be specialized by the implementation to be no less efficient than iter += 2 when used with random-access iterators.

    0 讨论(0)
  • 2020-12-04 16:55

    If you don't know wether you have enough next elements in your container or not, you need to check against the end of your container between each increment. Neither ++ nor std::advance will do it for you.

    if( ++iter == collection.end())
      ... // stop
    
    if( ++iter == collection.end())
      ... // stop
    

    You may even roll your own bound-secure advance function.

    If you are sure that you will not go past the end, then std::advance( iter, 2 ) is the best solution.

    0 讨论(0)
提交回复
热议问题