c++作用域问题:创建一个矩阵类而不浪费空间

C++ Scope issue: Creating a matrix class without wasting space

本文关键字:空间 一个 问题 作用域 创建 c++      更新时间:2023-10-16

有一个小类让我很困扰:

class matrix{
    string name;
    int rowSize, columnSize;
    // I could declare double m[100][100]; here but that would be ugly
    public:
    void createMat(){
        cout << "Enter Matrix Name:"; 
        cin >> name;
        cout << "Enter number of rows: "; 
        cin >> rowSize;
        cout << "Enter no. of columns: "; 
        cin >> columnSize; 
        double m[rowSize][columnSize]; //needs to be available to readMat()
        cout << "Enter matrix (row wise):n";
        for(int i = 0; i < rowSize; i++){
            for(int j = 0; j < columnSize; j++){cin >> m[i][j];}
            cout<<'n';
        }
    }
    void readMat(){
        cout << "Matrix " << name << " :n";
        for(int i = 0 ; i < rowSize; i++){
        for(int j = 0; j < columnSize; j++){ cout << m[i][j] << ' ';}
        cout<<'n';
        }
    }
};

如何以最优的方式使mcreateMat()readMat()都可用?

尝试允许用户输入矩阵的维度是不必要的吗?

从我的角度来看,我觉得定义矩阵的最大大小在需要更多元素的情况下会过于限制,或者如果不需要那么多元素的话会太多。

您应该使用动态大小的内存块,并在运行时根据用户输入分配它。这里,我使用std::vector:

class matrix{
    std::string name;
    int rowSize, columnSize;
    std::vector<double> m;
    public:
    void createMat(){
        std::cout << "Enter Matrix Name:"; 
        std::cin >> name;
        std::cout << "Enter number of rows: "; 
        std::cin >> rowSize;
        std::cout << "Enter no. of columns: "; 
        std::cin >> columnSize; 
        m.resize(rowSize*columnSize);
        std::cout << "Enter matrix (row wise):n";
        for(int i = 0; i < rowSize; i++){
            for(int j = 0; j < columnSize; j++){
                std::cin >> m[i*columnSize+j];
            }
            std::cout<<'n';
        }
    }
    void readMat() {
        std::cout << "Matrix " << name << " :n";
        for(int i = 0 ; i < rowSize; i++){
            for(int j = 0; j < columnSize; j++) {
                std::cout << m[i*columnSize+j] << ' ';
            }
            std::cout<<'n';
        }
    }
};

我对你的问题的回答是:

  1. 使其成为类成员(听起来很明显,但你期望什么样的答案?)
  2. 很可能允许用户设置矩阵大小是有意义的…但这真的取决于你需要什么。

我会做一些不同的事情,特别是:

  • 代替createMat(),我将使用类构造函数来执行初始化杂务(构造函数的存在正是因为这个原因)。

  • 然后我将元素存储在private 1D数组element[rowSize*columnSize]中(在构造函数中动态分配)。

  • 然后创建void setElement(i,j)double getElement(i,j)方法

(考虑查看EIGEN库,这是一个非常光滑且易于使用的线性代数库,带有一些类似matlab的味道)

您需要将m定义为类成员并进行动态内存分配。

class matrix{
    string name;
    int rowSize, columnSize;
    double **m;
    void createMat(){
       m = new double*[rowSize];
       for(int i = 0; i < rowSize; ++i)
          m[i] = new double[columnSize];
    }
 }

这里有详细的教程:http://www.cs.umb.edu/~mweiss/cs410_f04/ppts/cs410-7.pdf

相关文章: