Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[].
To access arbitrary elements in a vector vec
, you can use the following:
1st: vec.begin()
2nd: vec.begin()+1
3rd: vec.begin()+2
4th: vec.begin()+3
...
ith: vec.begin()+(i-1)
...
last: vec.begin()+(vec.size()-1)
The following is an example of a typical access pattern using an iterator.
int sum = 0;
for (std::vector<int>::const_iterator it = vec.begin(); it!=vec.end(); ++it) {
sum += *it;
}
The advantage of using iterator is that you can apply the same pattern with other containers:
int sum = 0;
for (std::list<int>::const_iterator it = lst.begin(); it!=lst.end(); ++it) {
sum += *it;
}
For this reason, it is really easy to create template code that will work the same regardless of whether the container is a vector, a list, or some other container. Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).