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!
ptris a raw pointer, it's not a class instance, therefore, it does not have any member functions such asbeginorend. You can iterate fromptrtoptr + row(exclusive). Pointers, in fact, are (random-access) iterators.