我研究了两种不同的方法来为矩阵的元素分配内存
方法一
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
方法二
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 子句,它确实...)
编辑:这是显示我的问题的代码。为什么加载需要这么长时间(~30 秒)?
Codepad 拒绝显示输出(超时),因此如果您想运行它,只需自行编译即可。
另外,为什么cout <<语句在程序启动后不执行?
最佳答案
方法 n.3:编写自己的 Matrix 类,在内部使用单个 std::vector<int>
并巧妙地通过(行,列)索引进行访问。
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 vector 的内存开销是上一个示例中的一个问题,您可以考虑使用长度为 rows*cols
的单个动态分配数组, 并确保调用 delete []
在析构函数中对其进行处理。
关于C++ 内存分配。矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926763/