What happens if you increment an iterator that is equal to the end iterator of an STL container

前端 未结 8 1533
别那么骄傲
别那么骄傲 2020-11-27 05:46

What if I increment an iterator by 2 when it points onto the last element of a vector? In this question asking how to adjust the iterator to an STL container by 2 elements t

8条回答
  •  误落风尘
    2020-11-27 06:32

    container.end() -- the element just past the end -- is the only defined exterior value.

    A checked iterator will fault on what is essentially an out-of-range access, but that isn't terribly helpful (especially as the default behaviour is to end the program).

    I think the best practice is "don't do that" -- either check every value of the iterator (preferably in something wrapped as a filter), and only operate on interesting entries, or use the index explicitly with

    for(int i = 0; i < vec.size(); i+=2) {...}
    

提交回复
热议问题