How to increment an iterator by 2?

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

    http://www.cplusplus.com/reference/std/iterator/advance/

    std::advance(it,n);
    

    where n is 2 in your case.

    The beauty of this function is, that If "it" is an random access iterator, the fast

    it += n
    

    operation is used (i.e. vector<,,>::iterator). Otherwise its rendered to

    for(int i = 0; i < n; i++)
        ++it;
    

    (i.e. list<..>::iterator)

提交回复
热议问题