Skip to main content

8.5) Using An Iterator: Examples


1. Using const_iterator to display the elements of a vector:

vector<double> v;
...
vector<double>::const_iterator i;
for (i = v.begin(); i != v.end(); ++i) {
  cout << (*i) << endl;
}

Note the use of != in the for loop (required) and use of * to dereference the iterator. (The brackets around *i aren't strictly necessary here, but using them can improve readability when the dereferenced value appears as part of an expression.)

2. Using const_iterator to display the first 5 elements of a vector:

vector<double> v;
...
vector<double>::const_iterator i;
for (i = v.begin(); i != v.begin()+5; ++i) {
  cout << (*i) << endl;
}

v.begin() points to the start of the vector and v.begin()+5 points just past the first five elements.

3. Using iterator to modify the elements of a vector:

vector<int> v;
...
for (vector<int>::iterator i = v.begin(); i != v.end(); ++i) {
  (*i) += 1;
}