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

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

    You could use the "distance" function between your iterator (it) and the iterator at vec.begin() and compare it with the vector's size (obtained by size()).

    In that case your for loop would look like this:

    for (vector::iterator it = vec.begin(); distance(vec.begin(), it) < vec.size(); ++it)
    {
         // Possibly advance n times here.
    }
    

提交回复
热议问题