@naraku9333. Thanks for that iterator code.
I will tinker with iterators for the above class once I'm working with a template version.
I have found various codes for an iterator class online.
What I couldn't picture was how to create an object (iterator) which behaves entirely as though it is another type (pointer to T), without ever referring to it's data members. I see that this behavior is "teased out" through the creative definition of operators.
Did you copy your operator-> correctly? It returns the same as operator* (namely T&).
I found one operator-> definition for an iterator particularly interesting.
Check this:
this <--pointer to iterator
*this <--- reference to iterator
**this <--- reference to T (left * interpreted as our overload for * in iterator class)
&(**this) <--- pointer to T
Hence:
1 2 3 4
|
T* iterator::operator->()
{
return &(**this);
}
|
Also, I came across the real hardcore stuff. Here's a link to an article which explains how to define an iterator class so that it is fully compatible with the STL algorithms. ie, so you can call std::sort(), etc on your own containers.
There are numerous typedefs, iterator "traits", and an inheritance heirarchy (where eg. iterator derives from const_iterator, etc,..).
So, spoiler alert! Every detail for creating a singly linked list that is fully compatible with the standard STL methods is here:
http://en.literateprograms.org/Singly_linked_list_%28C_Plus_Plus%29
@devonrevenge: Gets deep fast, huh?
I'm only a couple of steps ahead of you.
EDIT: Readers may wish to add front() and back() functions (both returning T&). The issue of what to return if the list is empty will arise.
This issue is discussed in detail, and some valuable examples of exception handling code, can be found in this other thread (currently active in the general programming forum)
http://www.cplusplus.com/forum/general/85346/
I have linked to the beginning of the thread. See pg. 2 re. above issues.