[英]constructor function for a 3x3 matrix (C++)
我需要为我的 3x3 矩阵 class 编写构造函数。 我不确定我是否有效地执行它并且我不知道如何使用 initializer_list.. 我想要一个默认创建单位矩阵并接收参数以设置对角矩阵的构造函数。 然后我还想要一个构造函数,它接受一个系数列表(带有initialization_list)并将它们放入矩阵中。 这就是我所拥有的:
#include <iostream>
#include <array>
#include <cmath>
#include <initializer_list>
#include "Vecteur.h"
using namespace std;
class Matrice33 {
private :
array<array<double,3>,3> matrice;
public :
Matrice33(double a = 1, double b=1, double c=1)
{ matrice[0][0] = a; matrice[1][1]= b; matrice [2][2]= c;
matrice[0][1] = 0; matrice[0][2] = 0;
matrice[1][0] = 0; matrice[1][2] = 0;
matrice[2][0] = 0; matrice[2][1] = 0;} \\ IS THIS THE ONLY WAY TO SET THE MATRIX OR IS
\\THERE A QUICKER ONE?
Matrice33(initilizer_liste<double> cosnt& coeff)
{ for( auto c : coeff) \\ I DON'T KNOW HOW TO WRITE THIS CONSTRUCTOR...
void affiche() const { for(auto m : matrice){
for(auto n : m) {
cout<<n<<" ";}
cout<<endl;}}
};
int main(){
Matrice33 mat(1.1, 1.2, 1.3,
2.1, 2.2, 2.3,
3.1, 3.2, 3.3); \\I'D LIKE THIS TO BE TAKEN AS THE LIST BY MY CONSTRUCTOR, FOR
\\EXAMPLE
Matrice33 m(2.0,3.0,1.0);
m.affiche(); \\ WHEN I EXECUTE I DON'T GET ANY OUTPUT..
return 0;
}
这是您正在运行的代码的更改版本。
#include <iostream>
#include <array>
#include <cmath>
#include <initializer_list>
#include <vector>
using namespace std;
class Matrice33
{
public:
Matrice33(double a = 1, double b = 1, double c = 1)
: matrice{{ {{a, 0, 0}}, {{0, b, 0}}, {{0, 0, c}} }}
{
}
Matrice33(const std::initializer_list<std::initializer_list<double>> & coeff)
{
int counter = 0;
for (auto row : coeff)
{
copy(row.begin(), row.end(), matrice[counter++].begin());
}
}
void affiche()
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << matrice[i][j] << " ";
}
cout << endl;;
}
}
private:
array<array<double, 3>, 3> matrice;
};
int main()
{
Matrice33 mat{ {1.1, 1.2, 1.3},{2.1, 2.2, 2.3},{3.1, 3.2, 3.3} };
mat.affiche();
Matrice33 m(2.0, 3.0, 1.0);
m.affiche();
return 0;
}
您可以在此处使用完美转发和模板构造函数。
template<typename... Args>
Matrice33(Args&&... args) : matrice(std::forward<Args>(args)...) {}
那么初始化将与 std::array 的初始化相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.