Use of iterators over array indices

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

    The STL contains algorithms, such as transform and for_each that operate on containers. They don't accept indices, but use iterators.

    Iterators help hide the container implementation and allow the programmer to focus more on the algorithm. The for_each function can be applied to anything that supports a forward iterator.

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

    I would say it's more a matter of consistency and code reuse.

    • Consistency in that you will use all other containers with iterators
    • Code reuse in that algorithms written for iterators cannot be used with the subscript operator and vice versa... and the STL has lots of algorithms so you definitely want to build on it.

    Finally, I'd like to say that even C arrays have iterators.

    const Foo* someArray = //...
    const Foo* otherArray = new Foo[someArrayLength];
    
    std::copy(someArray, someArray + someArrayLength, otherArray);
    

    The iterator_traits class has been specialized so that pointers or a model of RandomAccessIterator.

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

    One other slight difference is that you can't use erase() on an element in a vector by index, you must have an iterator. No big deal since you can always do "vect.begin() + index" as your iterator, but there are other considerations. For example, if you do this then you must always check your index against size() and not some variable you assigned that value.

    None of that is really too much worth worrying about but if given the choice I prefer iterator access for the reasons already stated and this one.

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