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

前端 未结 7 1223
萌比男神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 08:02

    That depends on what you need:

    If you need genericity, use std::advance(it,2). If someone comes along and changes your std::vector into a std::list, the code will still compile, even though advancing now takes linear time instead of constant time.

    If you need performance, use it+=2. If someone comes along and changes your std::vector into a std::list, the code will fail to compile, pointing (maybe with a helpful comment) at a serious performance issue.

提交回复
热议问题