Search code examples
c++arraysdynamic-memory-allocation

C++: using iterator to construct a 2D dynamically allocated array


I'm new to C++, and I am trying to create a class with a constructor that allocates a 2D array dynamically. I tried to use for loop with iterators(like: for(auto itr = arr.begin(); itr! = arr.end(); itr++))and found out that I can't use .begin() with pointers.

Following is my code:

class Myarray {
public:
    Myarray(std::size_t a, std::size_t b) : row(a), col(b) {
        ptr = new int* [row];
        for (auto itr = ptr->begin(); itr != (*ptr).end(); itr++) {
        itr = new int[col];
        }
    }
    //Myarray(Myarray& arr) {}; copy constructor, not filled yet
    //~Myarray() {}; destructor, not filled yet

private:
    std::size_t row, col;
    int** ptr;

};

I'm not sure why both (*ptr).end() and ptr->begin() don't work. My guess is: ptr is supposed to point to the first entry of an array, so I can't use .end() and begin() with that.

(1) Am I correct about this? (2) Is there any method I can dynamically allocate arrays with iterators?

Thanks for your answers!


Solution

  • I am trying to create a class with a constructor that allocates a 2D array dynamically

    Thing about dynamic 2D arrays is that only their outermost dimension can be dynamic. It appears that you want two dynamic dimensions. That is not possible for 2D array in C++.

    It also appears that you are not creating a 2D array, but rather an array of pointers, where each pointer points to an array of integers, so the limitation mentioned above is not a problem.

    I'm not sure why both (*ptr).end() and ptr->begin() don't work.

    . is the member access operator. ptr points to a pointer. Pointers do not have members.

    My guess is: ptr is supposed to point to the first entry of an array, so I can't use .end() and begin() with that.

    (1) Am I correct about this?

    Yes ptr points to the pointer that is the first element of the dynamic array of pointers.

    (2) Is there any method I can dynamically allocate arrays with iterators?

    I don't quite understand this sentence, but that may be because you don't quite know what these words mean yet.

    Pointers are iterators for arrays. So, given that ptr is a pointer to the first element of the array, and you want iterator to the first element, well ptr is the iterator that you want.

    You also want the end iterator. You can get that with pointer arithmetic. Simply add the length of the array to the begin to get to the end: ptr + row.


    P.S. Don't use owning bare pointers. Use RAII containers such as std::vector to create a dynamic array.