Are Iterators faster than array[i]? [duplicate]
Possible Duplicate:
Why use iterators instea开发者_JAVA技巧d of array indices?
Because for the life of me I can't figure out how they're not redundant.
vector<string>::iterator iter1
vector<string>::const_iterator iter2
Maybe they're faster?
Iterators aren't intended to be faster, they're intended to be as fast, which they are, and significantly more generic. array[i]
is only valid for an array- not a linked list.
Iterators allow container independent algorithms to be developed. This way something like std::sort
doesn't really have to care whether it is a vector
or your_datastructure_here
as long as it meets the appropriate iterator requirements.
Consider finding the maximum in a list
, vector
, or bare array.
int A[...]; // ...some array
std::list<int> L; // ...some list
std::vector<int> V; // ...some vector
int* maxA = std::max_element(A, A + 10);
std::list<int>::iterator maxL = std::max_element(L.begin(), L.end());
std::vector<int>::iterator maxV = std::max_element(V.begin(), V.end());
In the simple case of "random access" through a vector? No.
In fact, your vector iterator is probably defined in terms of array access, and will be precisely as quick.
What you gain is the ability to use them in generic programming. You may not always be using a vector, and not all containers support random access.
Use iterators not only for consistency, but for the ability to leverage template metaprogramming that such consistency affords you.
And, if nothing else, they're a safe and helpful abstraction.
They generalize to other collections where array[i] is much slower (i. e. lists) or even impossible (recordsets).
Also, STL algorithms use them. The STL algorithms were designed to work with any iterable collection - why exclude vectors?
The existence of two iterators - one const
and the other not - is motivated by the way const references work in C++. If all you have is a const
ref to a vector, why should you be able to change the stuff inside? Thus const_iterator
. The regular iterator
returns a writable reference to an element.
Iterators is a generic concept. They work on all sorts of containers and have similar interface.
Accessing the array element directly like arr_int[i]
is definitely faster because it directly translates to pointer arithmetic.
精彩评论