Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of iterators over array indices

Tags:

c++

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.

like image 857
PrithviRaj Avatar asked Mar 25 '10 12:03

PrithviRaj


People also ask

What are the advantages of iterators over arrays?

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.

Are iterators faster than indexing?

Depending on the actual container, incrementing an iterator might be faster than indexing (think linked lists).

What is difference between iterator and index?

An index (or key) is used to look up data in a container. The simplest case would be the integer indexes of an array, but containers like std::map can have nearly any type as an index. An iterator is a class which represents a position in a container.

Why should I use iterators?

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.


2 Answers

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).

like image 121
T.E.D. Avatar answered Sep 18 '22 19:09

T.E.D.


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.

like image 42
Michael Kristofik Avatar answered Sep 18 '22 19:09

Michael Kristofik