我想创建一个类似于指向二维指针数组的指针(宽度和高度为 x
)。
这段代码会达到我的预期吗? (创建数组元素,写出关于它们的一些信息,然后释放所有分配的内存。)
int main(int argc, char** argv) {
int x = 3;
Node ***array = new Node**[x];
for (int i = 0; i < 3; i++) {
array[i] = new Node*[x];
for (int j = 0; j < x; j++) {
array[i][j] = new Node(i, j); /* Node::Node(int row, int col) */
}
}
/* ....... */
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
cout << array[i][j]->row << ", " << array[i][j]->col << endl;
}
}
/* ....... */
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
delete array[i][j];
//array[i][j] = NULL;
}
delete[] array[i];
//array[i] = NULL;
}
delete[] array;
//array = NULL;
return 0;
}
或者我应该创建一个 vector
的 vector
指向 Node
对象的指针?
或者我应该在堆栈上分配我的对象吗?
(我使用的是指针,因为在 Java 或 C# 中,创建对象时必须始终使用 new
关键字(但是,我不认为所有对象都在堆中内存),我读到堆上有更多可用空间。)
我使用带有 new
关键字的指针的另一个原因是我想创建指向同一对象的多个指针。
我应该在堆栈上创建一个对象,然后只创建指向该对象的指针吗?
最佳答案
我建议您使用 vector< vector<Node> >
, boost::multi_array ,或者您可以汇总自己的动态 2D 数组类(并不难),它是平面 1D 的包装器 std::vector
.
上述所有解决方案都会将您的 Node 对象存储在堆中,并负责清理内存。
这是一个简单的 Matrix 类示例,它是 std::vector<T>
的包装器:
#include <iostream>
#include <vector>
template <class T>
class Matrix
{
public:
Matrix() : width_(0), height_(0), vec_(0) {}
Matrix(size_t width, size_t height)
: width_(width), height_(height), vec_(width*height) {}
size_t size() const {return vec_.size();}
size_t width() const {return width_;}
size_t height() const {return height_;}
// Clears all preexisting data
void resize(size_t width, size_t height)
{width_ = 0; height_ = 0; vec_.clear(); vec_.resize(width*height);}
void clear() {width_ = 0; height_ = 0; vec_.clear();}
T& operator()(size_t col, size_t row) {return vec_[row*width_ + col];}
const T& operator()(size_t col, size_t row) const
{return vec_[row*width_ + col];}
private:
size_t width_;
size_t height_;
std::vector<T> vec_;
};
int main()
{
Matrix<double> a(3, 4);
a(1, 2) = 3.1415;
std::cout << a(1,2) << "\n";
}
它使用 operator()
模仿 array[2][4]
C风格多维数组的语法。您不必担心浅拷贝、释放内存等问题,因为 vector
已经处理好了。
关于c++二维数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5836425/