Advance iterator for the std::vector std::advance VS operator +?

前端 未结 7 1220
萌比男神i
萌比男神i 2021-02-07 07:36

I found myself writing the following a lot:

int location =2;
vector vec;
vector::iterator it=vec.begin();

/..../
std::advance(it, location         


        
7条回答
  •  伪装坚强ぢ
    2021-02-07 07:38

    std::adnvance is generic - it is useful if you don't always know type of underlying container - it works in all cases.

    Yet it is efficient: std::advance will do an optimisation if it passed an RandomAccessIterator (like one from std::vector) and will increase iterator in loop for ForwardAccessIterator (as like one in std::list).

提交回复
热议问题