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

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

    Perhaps you should have something like this:

    template 
    Itr safe_advance(Itr i, Itr end, size_t delta)
    {
        while(i != end && delta--)
            i++;
        return i;
    }
    

    You can overload this for when iterator_category is random_access_iterator to do something like the following:

    return (delta > end - i)? end : i + delta;
    

提交回复
热议问题