C++:使用迭代器构造二维动态分配数组
C++: using iterator to construct a 2D dynamically allocated array
我是 C++ 的新手,我正在尝试使用动态分配二维数组的构造函数创建 class。我尝试将 for 循环与迭代器一起使用(例如:for(auto itr = arr.begin(); itr!= arr.end(); itr++))并发现我不能使用 .begin( ) 与指针。
以下是我的代码:
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;
};
我不确定为什么 (*ptr).end() 和 ptr->begin() 都不起作用。我的猜测是:ptr 应该指向数组的第一个条目,所以我不能对它使用 .end() 和 begin()。
(1) 我说得对吗? (2) 有什么方法可以用迭代器动态分配数组?
感谢您的回答!
I am trying to create a class with a constructor that allocates a 2D array dynamically
关于动态二维数组的事情是只有最外层的维度可以是动态的。看来您需要两个动态维度。这对于 C++ 中的二维数组是不可能的。
看来您并不是在创建一个二维数组,而是一个指针数组,其中每个指针指向一个整数数组,因此上述限制不是问题。
I'm not sure why both (*ptr).end() and ptr->begin() don't work.
.
是成员访问运算符。 ptr
指向一个指针。指针没有成员。
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?
是ptr
指向动态指针数组第一个元素的指针。
(2) Is there any method I can dynamically allocate arrays with iterators?
我不太明白这句话,可能是因为你还不太明白这句话的意思
指针是数组的迭代器。因此,假设 ptr
是指向数组第一个元素的指针,并且您想要指向第一个元素的迭代器,那么 ptr
就是您想要的迭代器。
您还需要结束迭代器。你可以用指针算术得到它。只需将数组的长度添加到开头即可到达结尾:ptr + row
.
P.S。不要使用拥有裸指针。使用std::vector
等RAII容器创建动态数组。
我是 C++ 的新手,我正在尝试使用动态分配二维数组的构造函数创建 class。我尝试将 for 循环与迭代器一起使用(例如:for(auto itr = arr.begin(); itr!= arr.end(); itr++))并发现我不能使用 .begin( ) 与指针。
以下是我的代码:
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;
};
我不确定为什么 (*ptr).end() 和 ptr->begin() 都不起作用。我的猜测是:ptr 应该指向数组的第一个条目,所以我不能对它使用 .end() 和 begin()。
(1) 我说得对吗? (2) 有什么方法可以用迭代器动态分配数组?
感谢您的回答!
I am trying to create a class with a constructor that allocates a 2D array dynamically
关于动态二维数组的事情是只有最外层的维度可以是动态的。看来您需要两个动态维度。这对于 C++ 中的二维数组是不可能的。
看来您并不是在创建一个二维数组,而是一个指针数组,其中每个指针指向一个整数数组,因此上述限制不是问题。
I'm not sure why both (*ptr).end() and ptr->begin() don't work.
.
是成员访问运算符。 ptr
指向一个指针。指针没有成员。
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?
是ptr
指向动态指针数组第一个元素的指针。
(2) Is there any method I can dynamically allocate arrays with iterators?
我不太明白这句话,可能是因为你还不太明白这句话的意思
指针是数组的迭代器。因此,假设 ptr
是指向数组第一个元素的指针,并且您想要指向第一个元素的迭代器,那么 ptr
就是您想要的迭代器。
您还需要结束迭代器。你可以用指针算术得到它。只需将数组的长度添加到开头即可到达结尾:ptr + row
.
P.S。不要使用拥有裸指针。使用std::vector
等RAII容器创建动态数组。