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

前端 未结 7 1224
萌比男神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:58

    If you're never going to change the container (and you probably aren't), use + because it's easy to see and understand and leaves the code less cluttered.

    If you think you want to change the container, OR if you are working inside a template that might be instantiated on various container types, use advance because it works with anything.

    As a general rule, I don't worry about changing container types because I've found that when I do have to change a container type, I end up revisiting everywhere that container is used anyway, just to be sure I'm not doing anything that's suddenly stupid (like randomly plucking elements out of the middle of a list).

提交回复
热议问题