why does it need it!=obj.end() although every iterator should know itself when to terminate?

c++, containers, iterator

Solution

If the iterator API would be designed like that, a pointer wouldn't be a valid iterator (since a pointer obviously wouldn't have an `end()`) method. So that would rule out the most straight-forward way to implement iterators for data structures with contiguous memory.

Problem

the following question just shot through my head. For the c++ stl iterators, a common practice is to have something like: ``` for (iterator it=obj.begin(); it!=obj.end(); it++) ``` what I am wondering is actually that obj.begin() could have told "it" when to stop which would make the for loop look like: ``` for (iterator it=obj.begin(); !it.end(); it++) ``` The benefit would be to make the iterator more self contained, and one could save (iterator end()) in the container class.

Original source