C++ -- STL Vector::const_iterator why not use < xx.end()?
// display vector elements using const_iterator
for ( constIterator = integers.begin();
constIterator != integers.end(); ++constIterator )
cout << *constIterator << ' ';
开发者_如何学Go
Can we use constIterator < integers.end()
?
Thank you
operator<
is only defined for random access iterators. These are provided, for example, by std::vector
and std::string
, containers that, in essence, store their data in contiguous storage, where iterators are usually little more than wrapped pointers. Iterators provided by, e.g., std::list
are only bidirectional iterators, which only provide comparison for equality.
Traditionally, it's seen as defensive programming to use <
instead of !=
. In case of errors (for example, someone changes ++i
to i+=2
) the loop will terminate even though the exact end value is never reached. However, another view at this is that it might mask an error, while the loop running endlessly or causing a crash would make the error apparent.
Yes, and you can also use operator < for deque::(const_)iterator, but it won't work for iterators for any other containers.
The working of operator < is guaranteed because vector and deque provide a Random Access Iterator.
精彩评论