container iterators - should they be nested?

Should the custom iterator for a customer container be a nested class or a free(for a lack of better word) class? I have seen it both ways, especially in books and online, so not sure if one approach has advantage over other. The two books I am using both have the iterators defined as free classes where as online first few implementations I checked, all were nested.

I personally prefer nested iterator, if the iterator only serves a particular container.

Thanks, DDG

p.s. - The question is not about preference but about advantages of one approach over others.


The fact is that an iterator, it is built and used for a specific class, so there is no need for it to be defined outside. Since you only use it in coordination with your container.

Different thing if your iterator it is used by different classes, but I can't really find an example of where it could be useful.

Edit. Finally, to wrap up, both can be done and I don't think there are any advantages in terms of memory used or execution times. For a better understanding of this we should check difference between a nested class and a not-nested class, but I think is off-topic here.


the iterator only serves a particular container.

The main thing to know is how true this will be.


Depends on the amount of types of containers you will define and the implementations you are applying, it's quite possible for some of them using the exact same type of iterator.

For instance, you will likely find myArray::iterator and myVector::iterator have the exact same implementation. Similarly, mySet::iterator and myMap::iterator might be the same as well.

If that's the case, it might be better do something like this to avoid implementing the same iterator multiple times:

// iterators.h
template<typename T>
struct contiguous_iterator
{
    // implementation for array and set iterator
};
template<typename T>
struct rb_tree_iterator
{
    // implementation for set and map iterator
};
// contiguous_containers.h
template<typename T>
struct myArray
{
    using iterator = contiguous_iterator<T>;
    //...
};
// rb_tree_containers.h
template<typename Key, typename Value>
struct myMap
{
    using iterator = rb_tree_iterator<tuple<Key, Value>>;
    //...
};