Why use iterators instead of array indices?

前端 未结 27 2226
萌比男神i
萌比男神i 2020-11-22 15:45

Take the following two lines of code:

for (int i = 0; i < some_vector.size(); i++)
{
    //do stuff
}

And this:

for (som         


        
27条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 16:18

    Because it is more object-oriented. if you are iterating with an index you are assuming:

    a) that those objects are ordered
    b) that those objects can be obtained by an index
    c) that the index increment will hit every item
    d) that that index starts at zero

    With an iterator, you are saying "give me everything so I can work with it" without knowing what the underlying implementation is. (In Java, there are collections that cannot be accessed through an index)

    Also, with an iterator, no need to worry about going out of bounds of the array.

提交回复
热议问题