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 << ' '; 

Is it possible to use constIterator < integers.end() ?

thanks

+4
source share
2 answers

operator< defined only for random access iterators . They are provided, for example, by the std::vector and std::string containers, which, in essence, store their data in continuous storage, where iterators are usually slightly larger than wrapped pointers. The iterators provided by std::list , for example, are bidirectional iterators that provide only comparisons for equality.

Traditionally, as defensive programming, use < instead of != . In case of errors (for example, someone changes ++i to i+=2 ), the cycle will end even if the exact final value is never reached. However, another view of this is that it can mask the error, while a loop that runs endlessly or causes failures will make the error obvious.

+8
source

Yes, and you can also use the <operator for deque: :( const_) iterator, but it will not work for iterators for any other containers.

The operator <is guaranteed to work because the vector and deck provide a random access iterator.

+7
source

All Articles