Tony Johansson said:
Hello!
Why should an Iterator be used instead of using index when going through a
collection for example ArrayList
//Tony
There may or not be a speed advantage, but there is almost certainly a
maintainability advantage if your algorithms don't actually need
subscripting. Consider:
#include <vector>
typedef std::vector<double> t_coll;
t_coll c;
....
for (t_coll::iterator i = c.begin(); i != c.end(); ++i)
*i = 2.2;
Now let's say that after some new requirements come in you find that you
must frequently delete items from the middle of your collection. You need to
use a list instead of a vector for efficient performance. No problem:
#include <list> // change this
typedef std::list<double> t_coll; // and this
t_coll c; // same
....
for (t_coll::iterator i = c.begin(); i != c.end(); ++i) // same
*i = 2.2; // same
Now if you had written you loops as
for (unsigned i = 0; i < c.size(); ++i)
c
= 2.2;
you would have to change them all.