I've created a Linked List in C++ and want to implement an iterator for it so that I can do range loops: for (const int& i : list)
where Linked_List<int> list;
.
My idea is to create the Iterator
as part of the Linked_List
class like this:
This is what I got so far:
template <typename T>
class Linked_List
{
public:
struct Iterator;
struct Node;
public:
Linked_List();
~Linked_List() noexcept(false);
Linked_List(const Linked_List&) = delete;
Linked_List(Linked_List&&) = delete;
Linked_List& operator=(const Linked_List&) = delete;
Linked_List& operator=(Linked_List&&) = delete;
void push_back(T);
void push_front(T);
void pop_back();
void pop_front();
bool empty() const;
T back() const;
T front() const;
//void swap(T, T);
//void insert(Iterator, T);
//void erase(Iterator);
//Iterator begin() const;
//Iterator end() const;
private:
Node* head;
Node* tail;
};
template<typename T>
struct Linked_List<T>::Node
{
Node() : prev(nullptr), next(nullptr) {}
Node(T t) : value(t), prev(nullptr), next(nullptr) {}
Node* prev;
Node* next;
T value;
};
- Is this a good approach?
- Should I do error checking when incrementing the list to check if
current->next == tail
? If so, how do I do that? Because my Iterator doesn't have a list object with a tail.
Edit:
I'm not sure how to implement the struct Iterator;
, I get stuck when figuring out how to connect it with the list so that I can check if the current node returned from the iterator equals the tail in the list, in the Linked_List Iterator end() const
method.
Let's say I've implemented all the necessary operators for an iterator like this:
struct Iterator
{
T& operator*() const { return current->value; }
bool operator!=(const Iterator& rhs) { return (*_current != rhs._current); }
Iterator& operator++()
{
current = current->next;
return *this;
}
};
How would I go about implementing Iterator Linked_List<T>::begin() const;
and end()
now?
I imagine an imaginary user making an iterator object like this:
Linked_List<int>::Iterator it;
An idea is to have a public constructor with no parameters and a private constructor that takes a node as a parameter which _current
will be set to, and have the Linked_List
class as a friend.