Why use iterators instead of array indices?

iterator c++
vector c++
cpp iterator vs index
iterator index c++
array iterator c++
iterator math
indexing vs iterating
c++ iterator vs index performance

Take the following two lines of code:

for (int i = 0; i < some_vector.size(); i++)
{
    //do stuff
}

And this:

for (some_iterator = some_vector.begin(); some_iterator != some_vector.end();
    some_iterator++)
{
    //do stuff
}

I'm told that the second way is preferred. Why exactly is this?


The first form is efficient only if vector.size() is a fast operation. This is true for vectors, but not for lists, for example. Also, what are you planning to do within the body of the loop? If you plan on accessing the elements as in

T elem = some_vector[i];

then you're making the assumption that the container has operator[](std::size_t) defined. Again, this is true for vector but not for other containers.

The use of iterators bring you closer to container independence. You're not making assumptions about random-access ability or fast size() operation, only that the container has iterator capabilities.

You could enhance your code further by using standard algorithms. Depending on what it is you're trying to achieve, you may elect to use std::for_each(), std::transform() and so on. By using a standard algorithm rather than an explicit loop you're avoiding re-inventing the wheel. Your code is likely to be more efficient (given the right algorithm is chosen), correct and reusable.

Why do you use iterators instead of array indices in the STL library in , Note - I have removed the C language tag on this question. It is really annoying to see people thinking it's the same language or worse, c++ as an extension. Indices can be used only for the containers stored as contiguous memory like vectors or arrays. Iteratord can be used to iterate over any Container. Besides, STL algorithms are generic because we are able to pass iterators from any containers. 71 views


It's part of the modern C++ indoctrination process. Iterators are the only way to iterate most containers, so you use it even with vectors just to get yourself into the proper mindset. Seriously, that's the only reason I do it - I don't think I've ever replaced a vector with a different kind of container.


Wow, this is still getting downvoted after three weeks. I guess it doesn't pay to be a little tongue-in-cheek.

I think the array index is more readable. It matches the syntax used in other languages, and the syntax used for old-fashioned C arrays. It's also less verbose. Efficiency should be a wash if your compiler is any good, and there are hardly any cases where it matters anyway.

Even so, I still find myself using iterators frequently with vectors. I believe the iterator is an important concept, so I promote it whenever I can.

Introduction to Iterators in C++, We can use iterators to move through the contents of the container. A pointer can point to elements in an array and can iterate through them using the Code reusability: Now consider if we make v a list in place of vector in the above How to find index of a given element in a Vector in C++ � Header files in C/C++ with� Why use iterators instead of array indices? (26 answers) Closed 6 years ago. I have a question about the preference between iterator and subscripting.


because you are not tying your code to the particular implementation of the some_vector list. if you use array indices, it has to be some form of array; if you use iterators you can use that code on any list implementation.

Iterators in C++ STL, Iterators are used to point at the memory addresses of STL containers. 1. begin () :- This function is used to return the beginning position of the container. The special thing about iterators is that they provide the glue between algorithms and containers.For generic code, the recommendation would be to use a combination of STL algorithms (e.g. find, sort, remove, copy) etc. that carries out the computation that you have in mind on your data structure (vector, list, map etc.), and to supply that algorithm with iterators into your container.


6.17 — Introduction to iterators, Use the type std::array<int, 7> if your compiler doesn't support C++17. Looping using indexes is more typing than needed if we only use the index to Instead of calculating our own begin and end points, we can simply ask� Iterators power for loops So we've seen that Python's for loops must not be using indexes under the hood. Instead, Python's for loops use iterators. Iterators are the things that power iterables.


I'm going to be the devils advocate here, and not recommend iterators. The main reason why, is all the source code I've worked on from Desktop application development to game development have i nor have i needed to use iterators. All the time they have not been required and secondly the hidden assumptions and code mess and debugging nightmares you get with iterators make them a prime example not to use it in any applications that require speed.

Even from a maintence stand point they're a mess. Its not because of them but because of all the aliasing that happen behind the scene. How do i know that you haven't implemented your own virtual vector or array list that does something completely different to the standards. Do i know what type is currently now during runtime? Did you overload a operator I didn't have time to check all your source code. Hell do i even know what version of the STL your using?

The next problem you got with iterators is leaky abstraction, though there are numerous web sites that discuss this in detail with them.

Sorry, I have not and still have not seen any point in iterators. If they abstract the list or vector away from you, when in fact you should know already what vector or list your dealing with if you don't then your just going to be setting yourself up for some great debugging sessions in the future.

How to Access the Index of the Current Element in a Modern For , Indeed, consider this rather old-style loop: With C++98, iterators came along, and allowed to write this (if we simplify it with auto , that How can we use a modern for loop and get access to the index of the current element? The get (index) method will return bad data that makes very difficult to identify the real problem. A ConcurrentModificationException is a nice signal making us easy to find the problem and to handle the problem. This is another good reason to use an Iterator.


CS 225, We might need a single for loop for an array, two nested for loops for the pixels in an of for loop that you're probably familiar with: initialize an index variable to zero and Let's see what that code would look like if we used iterators instead:. Iterators play a critical role in connecting algorithm with containers along with the manipulation of data stored inside the containers. The most obvious form of an iterator is a pointer. A pointer can point to elements in an array and can iterate through them using the increment operator (++).


Iteration utilities � The Julia Language, It provides a mutable wrapper around an iterator and its iteration state. lowercase) julia> collect(Iterators.take(a, 3)) 3-element Array{Char,1}: 'b' 'c' 'd' julia> See the pairs(IndexLinear(), iter) method if you want to ensure that i is an index. The use of Iterators instead of Indexing. An iterator may allow the container object to be modified without invalidating the iterator. For instance, once an iterator has advanced beyond the first element it may be possible to insert additional elements into the beginning of the container with predictable results.


Iterating Over Arrays — NumPy v1.20.dev0 Manual, Arrays support the iterator protocol and can be iterated over like Python lists. the memory layout of the array instead of using a standard C or Fortran ordering. During iteration, you may want to use the index of the current element in a� The Iterator is a design pattern. The intent is to "provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation". If you write lots of code against an array you may have to change your code in lots of places if you some day want to use some other representation, like say a linked list.