我是 C++ 的新手,想要研究算法的实现,为此我需要为各种矩阵分配空间,我按以下方式执行(在本例中 DATA_TYPE 为双精度):
void initializeMatrix(DATA_TYPE**& matrix, int rows, int cols) {
matrix = new DATA_TYPE*[rows];
for (int j = 0; j < rows; j++) {
matrix[j] = new DATA_TYPE[cols];
}
}
这样我就可以访问矩阵内部的值,例如矩阵[i][j],回顾过去,虽然我发现这不是一个明智的决定,因为当我访问不同的行时,它们可能会存储在很远的内存中结果是我由于缺乏空间局部性而失去了性能。我如何重写这个函数,以便我仍然可以使用 DATA_TYPE*,但指向行的各种 DATA_TYPE* 指针以 #cols 间隔,并且可能还对齐。
以下实现是否有意义(在 Windows 上)?我知道我仍然会损失一些性能,因为每次调用矩阵 [i] [j] 时,我都会失去获取该行的内存地址的时间。有没有办法绕过它或至少改进它(也许将 DATA_TYPE* 存储在靠近值存储的位置)。
void initializeMatrix(DATA_TYPE**& matrix, int rows, int cols) {
size_t total_elements = rows * cols;
size_t alignment = sizeof(DATA_TYPE);
DATA_TYPE *start_index = (DATA_TYPE *)_aligned_malloc(total_elements * sizeof(DATA_TYPE), alignment);
matrix = (DATA_TYPE **)malloc(rows * sizeof(DATA_TYPE *));
for (int j = 0; j < rows; j++) {
matrix[j] = start_index+j*cols;
}
}
这是一个脑残的简单二维矩阵类:
template <class T>
struct Matrix {
Matrix(int rows, int cols) : rows(rows), cols(cols), m(rows * cols) {}
std::vector<T> m;
const int rows, cols;
T* operator[](int i) { return &m[i*cols]; }
const T* operator[](int i) const { return &m[i*cols]; }
};
operator[]
的重载允许你写:
double getMiddle(const Matrix<double>& m) {
return m[5][5];
}
并将其编译为单个指针计算。