Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of iterators? [duplicate]

Why should I use iterators?

For example if I have code like this:

for (int i = 0; i < vec.size(); i++)
   cout << vec[i];

what would be the advantage of writing

for (vector<int>::iterator it != vec.begin(); it != n.end(); ++it)
   cout << *it;

Also, why is writing i < vec.size() and i++ more common in the first example and it != begin() and ++it more common in the second example? What is the difference how you increment it and why not always use an equal sign?

I understand iterators can be useful in C++11 range-based for loops and some STD algorithms, but why should I do it in normal code, since it is more verbose?

like image 743
Konstantin Kowalski Avatar asked Oct 24 '25 20:10

Konstantin Kowalski


1 Answers

Well not all containers have random access so you can do lookup on an index, so to normalize the interface iterators are fairly useful. Consider std::list. It doesn't support random access via a [] operator.

Taking this into account, to work across many heterogeneous types of containers, many STL functions like std::copy take iterators.

like image 94
Doug T. Avatar answered Oct 26 '25 11:10

Doug T.