Use of iterators over array indices

前端 未结 9 1447
执念已碎
执念已碎 2020-12-18 22:54

I just wanted to know what is the main advantage of using the iterators over the array indices. I have googled but i am not getting the right answer.

相关标签:
9条回答
  • 2020-12-18 23:22

    All of the standard containers provide the iterator concept. An iterator knows how to find the next element in the container, especially when the underlying structure isn't array-like. Array-style operator[] isn't provided by every container, so getting in the habit of using iterators will make more consistent-looking code, regardless of the container you choose.

    0 讨论(0)
  • 2020-12-18 23:22

    There are many data structures, e.g. hash tables and linked lists cannot be naturally or quickly indexed, but they are indeed traversable. Iterators act as an interface that let you walk on any data structure without knowing the actual implementation of the source.

    0 讨论(0)
  • 2020-12-18 23:25

    To expand upon previous answers:

    1. Writing a loop with operator[] constrains you to a container that supports [] and uses the same index/size type. Otherwise you'd need to rewrite every loop to change the container.

    2. Even if your container supports [], it may not be optimal for sequential traversing. [] is basically a random-access operator, which is O(1) for vector but could be as bad as O(n) depending on the underlying container.

    3. This is a minor point, but if you use iterators, your loop could be more easily moved to using the standard algorithms, e.g. std::for_each.

    0 讨论(0)
  • 2020-12-18 23:27

    I presume you are talking about when using a vector, right?

    The main advantage is that iterator code works for all stl containers, while the array indexing operator [] is only available for vectors and deques. This means you are free to change the underlying container if you need to without having to recode every loop. It also means you can put your iteration code in a template and it will work for any container, not just for deques and vectors (and arrays of course).

    0 讨论(0)
  • 2020-12-18 23:29

    You can abstract the collection implementation away.

    0 讨论(0)
  • 2020-12-18 23:31

    As well as the points in other answers, iterators can also be faster (specifically compared to operator[]), since they are essentially iteration by pointer. If you do something like:

    for (int i = 0; i < 10; ++i)
    {
        my_vector[i].DoSomething();
    }
    

    Every iteration of the loop unnecessarily calculates my_vector.begin() + i. If you use iterators, incrementing the iterator means it's already pointing to the next element, so you don't need that extra calculation. It's a small thing, but can make a difference in tight loops.

    0 讨论(0)
提交回复
热议问题