How to make the for each loop function in C++ work with a custom class

Firstly, the syntax of a for-each loop in C++ is different from C# (it’s also called a range based for loop. It has the form:

for(<type> <name> : <collection>) { ... }

So for example, with an std::vector<int> vec, it would be something like:

for(int i : vec) { ... }

Under the covers, this effectively uses the begin() and end() member functions, which return iterators. Hence, to allow your custom class to utilize a for-each loop, you need to provide a begin() and an end() function. These are generally overloaded, returning either an iterator or a const_iterator. Implementing iterators can be tricky, although with a vector-like class it’s not too hard.

template <typename T>
struct List
{
    T* store;
    std::size_t size;
    typedef T* iterator;
    typedef const T* const_iterator;

    ....

    iterator begin() { return &store[0]; }
    const_iterator begin() const { return &store[0]; }
    iterator end() { return &store[size]; }
    const_iterator end() const { return &store[size]; }

    ...
 };

With these implemented, you can utilize a range based loop as above.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)