Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ -- STL Vector::const_iterator why not use < xx.end()?

Tags:

c++

   // display vector elements using const_iterator
   for ( constIterator = integers.begin();
      constIterator != integers.end(); ++constIterator )
      cout << *constIterator << ' ';

Can we use constIterator < integers.end()?

Thank you

like image 305
q0987 Avatar asked Dec 07 '22 00:12

q0987


1 Answers

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.

like image 50
sbi Avatar answered Dec 27 '22 11:12

sbi