C ++内存分配。矩阵 [英] C++ Memory allocation. Matrix
问题描述
我研究了两种不同的方法来为矩阵的元素分配内存。
I looked into two different method to allocate memory for the elements of a matrix
方法n.1
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
方法n.2
int** matrix = new int*[rows];
if (rows)
{
matrix[0] = new int[rows * cols];
for (int i = 1; i < rows; ++i)
matrix[i] = matrix[0] + i * cols;
}
我可以找出什么方法n.1,但我不能找出在方法n.2中应该做什么if子句(我将实现它没有,它不工作,与if子句,它...)
I can figure out what Method n.1 does, but I can't figure out what exactly is supposed to do the if clause in Method n.2 (I would implement it without and it doesn't work, with the if clause, it does...)
编辑:这是一个代码显示我的问题。为什么加载时间过长(约30秒)?
Here is a code showing my problem. Why does it take so long to load (~30seconds)?
键盘拒绝显示输出(超时),所以如果你想运行它,只需自己编译。
Codepad refuses to show the output (timeout) so if you want to run it, just compile it on your own.
此外,为什么cout<
Also, why cout << statements are not executed once the program starts?
推荐答案
方法n.3:编写自己的Matrix类,内部使用单个 std :: vector< int>
并且聪明地关于通过(row,col)索引访问。
Method n.3: write your own Matrix class, internally using a single std::vector<int>
and being clever about access by (row,col) indices.
struct Matrix
{
explicit Matrix(unsigned int rows, unsigned int cols) : data_(rows*cols), cols_(cols) {}
const int& operator()(unsigned int row, unsigned int col) const
{
return data_[row*cols_ + col];
}
private:
std::vector<int> data_;
unsigned int cols_;
};
编辑: iff 向量的内存开销是最后一个例子,你可以考虑使用单个动态分配的长度 rows * cols
的数组,并确保调用 delete []
在析构函数中。
iff the memory overhead of a vector is an issue in the last example, you can consider using a single dynamically allocated array of length rows*cols
, and make sure to call delete []
on it in the destructor.
这篇关于C ++内存分配。矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!