DEV Community

Brandon Fong
Brandon Fong

Posted on

Range-Based For Loop Implementation

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 

Enter fullscreen mode Exit fullscreen mode
  • 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; }
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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;
    }
};
Enter fullscreen mode Exit fullscreen mode

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more