Can raw pointers be used instead of iterators with STL algorithms for containers with linear storage?

One of the features of iterators being based on operator-overloading, is that pointers are already random-access iterators. This was a big design win in the early days of STL, as it made it easier to use algorithms with existing code (as well as making the interface more familiar to programmers). It’s perfectly reasonable to wrap an array, add typedef T* iterator; typedef const T* const_iterator, return &array[0] from your begin() and &array[size] from your end(), and then use your container with any iterator-based algorithm. As you already realise, this will work for any container where elements are contiguous in memory (such as an array).

You might implement ‘real’ iterators if:

  • You have a different-shaped container (such as a tree or list);
  • You want to be able to resize the array without invalidating the iterators;
  • You want to add debugging checks to your iterator use, for example to check if the iterator is used after being invalidated or after the container has been deleted, or to bounds-check;
  • You want to introduce type-safety, and make sure people can’t accidentally assign an arbitrary T* to a my_array::iterator.

I’d say this last advantage alone is well worth writing a trivial wrapper class for. If you don’t take advantage of C++’s type system by making different kinds of thing have different types, you might as well switch to Javascript 🙂

Leave a Comment