Home > Mobile >  container iterators - should they be nested?
container iterators - should they be nested?

Time:01-23

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.

CodePudding user response:

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.

CodePudding user response:

While there would be no definitive answer,
I prefer to define them outside.
And I disagree with ranghetto's claim

The fact is that an iterator, it is built and used for a specific class

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.

I implemented std::vector-like containers(notice plural form), including double-ended one, small-buffer optimized one, etc..
And they use same iterator implementation.
In general, defining iterators outside reduces unnecessary dependencies.

  •  Tags:  
  • Related