Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 477
guinny Avatar asked Dec 07 '22 15:12

guinny


2 Answers

Sometimes you want to do something other than iterate over the entire contents of a container. For example, you can create a pair of iterators that will iterate over only the first half of a container. So having a separate object to represent the end is more flexible since it allows the user more control of where to place the end of a range.

You are right that it is somewhat inconvenient for the most common case of iterating over everything. However, C++11 provides a range based for loop which makes looping over a whole container really easy, so like many things in programming, it's really just a matter of selecting the right construct to best express your intention.

like image 97
Davis King Avatar answered Dec 21 '22 22:12

Davis King


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.

like image 41
sepp2k Avatar answered Dec 21 '22 22:12

sepp2k