2

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?

The Coding Fox
  • 1,488
  • 1
  • 4
  • 18

2 Answers2

4

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.

Hajo Kirchhoff
  • 1,969
  • 8
  • 17
2

I would add these 6 member functions to Bag to make it useable in both const and non-const contexts:

template<typename DataType>
class Bag
{
    DataType* arr;
    int len, real_size;
public:
    using iterator = DataType*;
    using const_iterator = const DataType*;

    // Class methods
    const_iterator cbegin() const { return arr; }
    const_iterator cend() const { return arr + len; }
    const_iterator begin() const { return cbegin(); }
    const_iterator end() const { return cend(); }
    iterator begin() { return arr; }
    iterator end() { return arr + len; }
};
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108