How to increment an iterator by 2?

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

    We can use both std::advance as well as std::next, but there's a difference between the two.

    advance modifies its argument and returns nothing. So it can be used as:

    vector v;
    v.push_back(1);
    v.push_back(2);
    auto itr = v.begin();
    advance(itr, 1);          //modifies the itr
    cout << *itr<

    next returns a modified copy of the iterator:

    vector v;
    v.push_back(1);
    v.push_back(2);
    cout << *next(v.begin(), 1) << endl;    //prints 2
    

提交回复
热议问题