I am reading Bjarne Straustup's "Principles and Practices of Programming Using C ++" and I need to clarify the amazing bit that I found in section 25.5.3. The author claims that if we want to iterate over std::vector
, then using a loop variable, for example
for (vector<int>::size_type i = 0; i < v.size(); ++i)
less secure than using iterators for the vector
class:
for (vector<int>::iterator p = v.begin(); p != v.end(); ++p)
because, being an unsigned type, i
can overflow. He argues that a loop using iterators does not have such a limitation. I'm a bit confused, as I found out that size_type
guaranteed to be large enough to represent the largest possible vector, so a variable of type size_type
will never overflow in such a loop.
EDIT
To be more specific, he presents an example using a loop variable of type int
in front of two others, and then at the end he states:
" size_type
guaranteed to be unsigned, so the first (unsigned integer) form has one more bit to play than the previous version of int
. It can be significant, but it still gives only one bit of range (doubling the number of iterations that can be performed ). An iterator loop has no such limitation. "
Does not return vector<T>::size()
a vector<T>::size_type
? I do not see any restrictions.
source share