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

前端 未结 8 1503
别那么骄傲
别那么骄傲 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

    You could also do more comparisons in your for statement:

    for( vector::iterator it = vec.begin(); it != vec.end() && it+1 != vec.end(); it+=2 ) {
        //manipulate the element through the iterator here
    }
    

    I don't know how this would perform vs Kostas's suggestion, but it feels like it would be better for a small increment. Of course it would be pretty unmaintainable for a large increment since you need a check for each, but it is another option.

    I would definitely avoid it if at all possible. If you really need to increment by 2 values at a time, then consider having a vector of std::pair or a vector of a struct with 2 elements.

提交回复
热议问题