Suppose you have an array of ints. You've put some values in it and
now you want to print them. What will you do? You'll use a for loop:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
int main()
{
int my_array[5] = { 5, 4, 3, 2, 1 };
int i;
for (i = 0; i != 5; ++i)
std::cout << my_array[i] << std::endl;
return 0;
}
|
Easy, right? Well, it's easy because the elements of an array occupy contiguous memory locations.
There are many cases, though, where an array is not a good choice to store your data. You need
the advanced functionality provided by the complex data structure X. However, X doesn't store its
elements in contiguous memory locations, because it's inefficient. How will you iterate over these
elements, then? That's exactly the problem iterators solve:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
#include <list>
int main()
{
std::list<int> my_list;
my_list.push_back(5);
my_list.push_back(4);
my_list.push_back(3);
my_list.push_back(2);
my_list.push_back(1);
std::list<int>::const_iterator it;
for (it = my_list.begin(); it != my_list.end(); ++it)
std::cout << *it << std::endl;
return 0;
}
|