Pointer or class as an iterator?

I am writing a random access container in C ++. I use this in my code (well, in my real code I use all types of Allocator typedefs, this is easier to understand):

template<typename T, typename Allocator = std::allocator<T> > class Carray { public: // ... typedef T* iterator; typedef const T* const_iterator; // ... }; 

But I can also create another iterator class derived from std::iterator . This will add support for typedefs ( it::iterator_category , it::difference_type , etc.).

Now my question is, is there any overhead using an iterator class instead of a raw pointer? If so, how significant is this overhead and is it enough not to use the iterator class?

+4
source share
2 answers

You have an iterator category, difference type, etc. avalaibale is for you, even if you have a raw pointer. You see, there is this iterator_traits<> template that you should use. It is already specialized for pointers.

 iterator_traits<int*>::value_type // ... etc. //or iterator traits<my_custom_iterator>::value_type 
+2
source

If your iterator class just wraps a pointer, there is almost certainly no overhead.

It is ideal for using source pointers as iterators. However, some poorly written codes (including, as you suggest, code that tries to use nested typedefs directly instead of iterator_traits) may not compile. Some of the early standard libraries started with pointers for vector iterators and changed to preserve such bad code. This is really the only reason I think to worry about.

BTW - if possible, I would use Boost iterator support, rather than getting directly from std :: iterator; many subtle requirements will take care of you this way.

+2
source

All Articles