0

So I do have an array class made by myself:

#include <algorithm>

template <class T>
class myArray
{
private:
    int length;
    T *elements;
public:
    myArray()
    {
        this->length = 0;
        this->elements = nullptr;
    }

    myArray(int len)
    {
        this->length = len;
        this->elements = new T[len];
    }

    myArray(int* data, int len)
    {
        this->length = len;
        this->elements = new T[len];
        std::copy(data, data+len, this->elements);
    }

    ~myArray()
    {
        delete[] this->elements;
    }
};

I think that for now it works. I wanted to check if the elements I pass in the 3rd constructor are getting properly copied, so I wrote this:

int data[] = {1,2,3,4,5};
myArray<int> a (data, 5);
for (auto x: myArray)
{
    std::cout << x << '\n';
}

The question is what I have to write in the class, to make it return this->elements, when I just call myArray. I know that it is possibly trivial, but I don't know how to find it, actually how to call it, to make Google find the answer for me.

  • 1
    *"make it return this->elements, when I just call myArray"* -- Is that what you really want? Or do you want the for loop to iterate over your array properly? Because those two goals are not the same thing. – Benjamin Lindley Jul 26 '17 at 22:17
  • Implement a `begin()` and `end()` that returns a pointer to the beginning and past-the-end respectively. Also, you have a rule of 5 violation. You should also least implement a move constructor correctly. – Guillaume Racicot Jul 26 '17 at 22:23
  • The keyword here is _iterators_. In particular, see this answer https://stackoverflow.com/a/32621416/2920343 – CompuChip Jul 26 '17 at 22:23

1 Answers1

4

You need to implement begin and end member functions for your class (or as global functions in the same namespace as your class), which return iterators pointing to the first element, and one past the last element of your array. Since your class is backed by a contiguous array, you don't need to implement an iterator class, and can just use pointers.

// these are member functions, as they would be defined inside your class
T* begin() {
    return elements;
}

T* end() {
    return elements + length;
}

You should also implement const versions.

T const* begin() const {
    return elements;
}

T const* end() const {
    return elements + length;
}
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274