Use of iterators over array indices

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

提交回复
热议问题