when you loop a container, for example vector, what is the difference between using an iterator and the more simple element indexes? The first one makes sense to me, the second one somewhat makes sense, except it seems more complicated for the same thing. Unless there is an extra ability with the iterator, i hate the fact of so many more extra keystrokes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <string>
#include <vector>
int main(){
std::vector<std::string> v = {"index1", "index2"};
for (int i=0; i<v.size(); i++){
std::cout << v[i] << std::endl;
}
for(std::vector<std::string>::iterator it = v.begin(); it != v.end(); it++){
std::cout << *it << std::endl;
}
}
Not all containers support the subscript operator. For example consider std::list or std::forward_list. You can access elements of these containers only by using iterators. Also the range-based for statement uses iterators. on the other hand sometimes it is more convinient to use the subscript operator with arrays. The main advantage of using the subscript operator is that you can trace the number of elements you are processing.