I wrote the following code when trying to make a doubly-linked list with an internal STL-like iterator. I’ll just provide the header file with the non-relevant parts trimmed out for now.
My questions are…
-
The STL uses iterators in a certain way – specifically, you navigate over an STL container from the .begin() iterator up to but not including the .end() iterator. To do this the .end() iterator has to be one-past the end of the container. How would I implement this kind of semantic given what I’ve started with (this is the main question)?
-
Is there anything missing in the interface as it stands (with regard to the iterator class and things that should be present in it)?
Here’s the code:
template <typename T>
class Node
{
T data;
Node<T>* next;
Node<T>* prev;
};
template <typename T>
class LinkedList
{
public:
class Iterator
{
public:
Iterator() {}
explicit Iterator(const Node<T>& init) { current = init; }
//Dereference operator - return the current node's data.
inline T& operator*() { return current->data; }
//Prefix returns by reference.
inline Iterator& operator++() { current = current->next; return *this; }
inline Iterator& operator--() { current = current->prev; return *this; }
//Postfix returns non-reference and has int parameter to differentiate function signature.
inline Iterator operator++(int) { Iterator res = *this; current = current->next; return res; }
inline Iterator operator--(int) { Iterator res = *this; current = current->prev; return res; }
private:
Node<T>* current;
};
Iterator begin() { return Iterator(m_start); }
Iterator end() { return Iterator(m_end); }
private:
Node<T>* m_start;
Node<T>* m_end;
};
I’m aware that I may or may not have problems with the ++/– operators, but that doesn’t particularly bother me as I’ll work those out when I have enough code to do some testing on this. Feel free to drop hints though if you’re inclined 🙂
First node’s prev pointer is NULL, so is last node’s next pointer. One-past-the-end’s
currentpointer would be NULL.operator->