Why use iterators instead of array indices?

前端 未结 27 2134
萌比男神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:20

    Imagine some_vector is implemented with a linked-list. Then requesting an item in the i-th place requires i operations to be done to traverse the list of nodes. Now, if you use iterator, generally speaking, it will make its best effort to be as efficient as possible (in the case of a linked list, it will maintain a pointer to the current node and advance it in each iteration, requiring just a single operation).

    So it provides two things:

    • Abstraction of use: you just want to iterate some elements, you don't care about how to do it
    • Performance

提交回复
热议问题