矩阵类的列表初始化 [英] list initialization for a matrix class
本文介绍了矩阵类的列表初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写用于线性代数计算的矩阵类.我几乎写完了我想要的东西.但是我在创建使用列表初始化来创建矩阵的构造函数时遇到了一些麻烦. 这是我班的数据成员:
I am trying to write a matrix class for linear algebra calculations. I have almost finished writing what I wanted. but I have a little trouble in creating a constructor that uses list initialization to create a matrix. this is my class data members:
template <typename T>
class Matx
{
private:
// data members
//rows and columns of matrix
int rows, cols;
//pointer to pointer to type T
T** matrix;
这是我的初始化代码:
template <typename T>
Matx<T>::Matx(T* ptM[], int m, int n) : rows(m), cols(n)
{
matrix = new T*[rows];
for (int i = 0; i < rows; i++)
matrix[i] = new T[cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = *(ptM[i] + j);
}
主要:
double mat[][5] = { {5,5,-1,7,54},{4,-9,20,12,-6},{9,-18,-3,1,21},{ 61,-8,-10,3,13 },{ 29,-28,-1,4,14 } };
double* pm[5];
for (int i=0;i<5;i++)
pm[i]=mat[i];
Matx<double> yourMat = Matx<double>(pm, 5,5);
但是我认为有更好的方法来做到这一点. 我想要的是能够像数组一样初始化它.像这样的东西:
but I think there is a better way to do it. what I want is to be able to initialize it like arrays. something like this:
Matx<double> yourMat = { {5,5,-1,7,54},{4,-9,20,12,-6},{9,-18,-3,1,21},{ 61,-8,-10,3,13 },{ 29,-28,-1,4,14 } };
有可能吗?
推荐答案
绝对有可能,我已经使构造函数使用了类似类的初始化列表.像这样的构造函数就可以完成这项工作:
It is definitely possible, I have made constructors that use initializer lists for similar classes. A constructor like this should do the job:
template <typename T>
Matx<T>::Matx(std::initializer_list<std::initializer_list<T>> listlist) {
rows = (int)(listlist.begin()).size();
cols = (int)listlist.size();
matrix = new T*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new T[cols];
for (int j = 0; j < cols; j++) {
matrix[i][j] = (listlist.begin()+i)[j];
}
}
}
这篇关于矩阵类的列表初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文