Use of iterators over array indices

前端 未结 9 1462
执念已碎
执念已碎 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: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.

提交回复
热议问题