I was interested in learning how to make my Linked List class adhere to a range-based for loop. I eventually saw a really good stackoverflow response that helped me figure out how to do it. This is my attempt at showing you how I implemented this feature with minimal lines of code. I will be speaking in context of a Linked List class.
Recall this is what the CPP documentation says about the Range-Based For Loop:
for ( range-declaration : range-expression )
loop-statement
- range-declaration = the variable you are going to use to hold onto the node object
- range-expression = the Linked List class
What you need for your Linked List class are two things:
Two methods:
Iterator begin() { return this->first(); }
Iterator end() { return NULL; }
begin() returns the first node of your Linked List (note first() returns a class Node) and end() will return NULL to identify the end of the list.
- An Iterator class
Notice both methods return Iterator. This is a nested class inside the Linked List:
class Iterator {
private:
Node * _curr;
public:
Iterator(Node * n) : _curr(n) {}
L operator*() const {
return this->_curr->object();
}
Iterator & operator++() { // pre-inc
this->_curr = this->_curr->next();
return *this;
}
Iterator operator++(int) { // post-inc
Iterator old = *this;
this->operator++();
return old;
}
bool operator!=(const Iterator& i) {
return !(*this == i);
}
bool operator==(const Iterator& i) {
return this->_curr == i._curr;
}
};
What I needed in this class, respectfully, was: a constructor that allows me return a Node coming from my Linked Listsβs begin(); then overloaders for the iteration, comparisons, and casting. Nest this class inside of the LinkedList class.
Simple and it did the job. What I needed was an iterator class that handles the iterative requirements for the range-based for loop. I also need to provide two accessor methods in my LinkedList class so the for loop can use it. You can see a demonstration of using my LinkedList class here.
Top comments (0)