C++ C Iterators (Pointers)


Example

// This creates an array with 5 values.
const int array[] = { 1, 2, 3, 4, 5 };

#ifdef BEFORE_CPP11

// You can use `sizeof` to determine how many elements are in an array.
const int* first = array;
const int* afterLast = first + sizeof(array) / sizeof(array[0]);

// Then you can iterate over the array by incrementing a pointer until
// it reaches past the end of our array.
for (const int* i = first; i < afterLast; ++i) {
    std::cout << *i << std::endl;
}

#else

// With C++11, you can let the STL compute the start and end iterators:
for (auto i = std::begin(array); i != std::end(array); ++i) {
    std::cout << *i << std::endl;
}

#endif

This code would output the numbers 1 through 5, one on each line like this:

1
2
3
4
5

Breaking It Down

const int array[] = { 1, 2, 3, 4, 5 };

This line creates a new integer array with 5 values. C arrays are just pointers to memory where each value is stored together in a contiguous block.

const int* first = array;
const int* afterLast = first + sizeof(array) / sizeof(array[0]);

These lines create two pointers. The first pointer is given the value of the array pointer, which is the address of the first element in the array. The sizeof operator when used on a C array returns the size of the array in bytes. Divided by the size of an element this gives the number of elements in the array. We can use this to find the address of the block after the array.

for (const int* i = first; i < afterLast; ++i) {

Here we create a pointer which we will use as an iterator. It is initialized with the address of the first element we want to iterate over, and we'll continue to iterate as long as i is less than afterLast, which means as long as i is pointing to an address within array.

    std::cout << *i << std::endl;

Finally, within the loop we can access the value our iterator i is pointing to by dereferencing it. Here the dereference operator * returns the value at the address in i.