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

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

    It depends on the iterator. it=it+5 is faster if it's supported (it's only supported on random access iterators). If you want to advance a less-capable iterator (e.g. a forward iterator, or a bidirectional iterator), then you can use std::advance, but it's slower because it actually walks across all of the intermediate elements.

提交回复
热议问题