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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With