How to increment an iterator by 2?

前端 未结 8 1717
眼角桃花
眼角桃花 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:51

    If you don't have a modifiable lvalue of an iterator, or it is desired to get a copy of a given iterator (leaving the original one unchanged), then C++11 comes with new helper functions - std::next / std::prev:

    std::next(iter, 2);          // returns a copy of iter incremented by 2
    std::next(std::begin(v), 2); // returns a copy of begin(v) incremented by 2
    std::prev(iter, 2);          // returns a copy of iter decremented by 2
    

提交回复
热议问题