Click to See Complete Forum and Search --> : For-loop: Vector Iterator vs. Vector.at() or []


alexin
February 14th, 2008, 12:12 PM
Supposing I want to access a vector's data sequentially using a for-loop, should I use an iterator or can I simply access elements with at() or []?

I want to know about the advantages or disadvantages.

Lindley
February 14th, 2008, 12:19 PM
In the case of a vector, I'm not sure it makes much difference.

The advantage of using an iterator is that the same code would work if you later decided to swap in, say, a set instead.

Philip Nicoletti
February 14th, 2008, 01:56 PM
1) As mentioned above, using iterators increases the ability
to write generic functions. Also, in debug mode, some
iterators have validity checks in them.

2) Operator [] tends to be more readable since the code looks
like code using simple c-style arrays.

3) at() will throw an exception if the index is out of range.

alexin
February 14th, 2008, 02:10 PM
Thank you. That elucidates me.