问题
I looked into two different method to allocate memory for the elements of a matrix
Method n.1
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
Method 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;
}
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...)
EDIT: Here is a code showing my problem. Why does it take so long to load (~30seconds)?
http://codepad.org/uKvI8Tk3
Codepad refuses to show the output (timeout) so if you want to run it, just compile it on your own.
Also, why cout << statements are not executed once the program starts?
回答1:
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_;
};
Edit: 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.
回答2:
Method n.2 is allocating a unique block to contain the sequence of all rows. Hence the first row is a pointer to the whole block. If rows==0 you have not space to hold the pointer to the (empty) space, so you cannot make the allocation.
I would steer toward method 4 suggested in the other answer:
class Matrix {
Matrix(int rows, int cols): rows_(rows), cols_(cols) {
data_ = new int[rows*cols];
}
~Matrix() {
delete[] data_;
}
int &operator()(int i,int j) {return data_[cols_*i+j];}
int operator()(int i,int j) const {return data_[cols_*i+j];}
private:
int rows_,cols_;
int *data_;
};
来源:https://stackoverflow.com/questions/14926763/c-memory-allocation-matrix