Search code examples
c++containers

Creating a suitable begin() and end() function for a class


I have the following class:

template<typename DataType>
class Bag
{
    DataType* arr;
    int len, real_size;
public:
    // Class methods
};

I have implemented different methods such as add, remove, etc. for Bag. I have also overloaded the operator[].

While testing this out, I wanted to print all the elements of an object of type Bag. So I tried this:

#include <iostream>

#include "bag.h"

int main()
{
    sgl::Bag<int> bag{};
    
    bag.add(12);
    bag.add(14);
    bag.add(16, 0);

    for (auto& i : bag) // this range-based 'for' statement requires a suitable "begin" function and none was found
    {

    }
}

As I got this error, I tried implementing begin() and end() as such:

DataType begin()
{
    return arr[0];
}
DataType end()
{
    return arr[len - 1];
}

But then I got the following error:

the iterator type in this range-based 'for' statement is "int", which is not a pointer type or an iterator-like class type

So my question is that how do I properly implement a suitable begin() and end() function for my class Bag?


Solution

  • begin and end need to return iterators/pointers to the first and the last+1 element, whereas you return the first and last element.

    DataType *begin() const { return arr; }
    DataType *end() const { return arr+len; }
    

    should work, assuming that len is the number of elements in your array.


    Note: end needs to point beyond the last element of your array, not at the last element. See cppreference.