我正在尝试为矩阵数据结构创建模板,我想以一种简洁直观的方式来索引和分配元素(即“ A(i,j)”返回元素,而“ A(i,j)= x '为此元素分配一个值。)
在其他论坛线程的基础上,我看到通过按引用返回数组元素,函数/运算符可以通过这种方式返回和更改该元素。
template <typename T, int Rows, int Cols>
struct Matrix {
private:
public:
const int rows = Rows; //number of rows
const int cols = Cols; //number of columns
T data[Rows*Cols]; //contents of matrix
//Single element indexing and assigment
T& operator() (int i, int j) {
return data[ (i-1)*(this->cols) + j ];
}
};
int main(){
const int m = 3;
const int n = 4;
Matrix<float, m, n> A;
for (int i = 0; i < A.rows; i++) {
for (int j = 0; j < A.cols; j++) {
A(i,j) = 3.14;
}
}
return 0;
}
当我尝试使用显式类型的结构(在本例中为int)而不是模板时,这种方法非常有效,但是现在我使用的是模板,因此赋值'A(i,j)= x'可以修改索引“ i”和“ j”通常会中断循环并导致分段错误。
有谁知道为什么会这样,是否有什么我可以做以达到预期效果的?
我对C ++相当陌生,因此如果我违反最佳实践,请随时让我知道该语言
用于索引的公式data
不正确。
更新您的函数以data[0]
始终返回但打印索引。输出将清楚表明您没有使用正确的索引。
T& operator() (int i, int j) {
int index = (i-1)*(this->cols) + j;
std::cout << "Index: " << index << std::endl;
return data[0]; // This is wrong but that's not the
// purpose of this suggested change.
}
有用的链接:如何调试小程序
PS正确的索引是i*(this->cols) + j
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句