用c ++创建矩阵

问题描述 投票:-1回答:3

我对C ++编程比较陌生,我想通过编程矩阵来学习更多有关语言的知识。我有这个代码可以工作,但我无法弄清楚如何创建适用于任何数量的列和行的代码。我无法将矩阵传递给函数,函数具有由用户输入确定的行和列。

这就是我所拥有的:

#include <iostream>

using namespace std;

template <int rows, int cols>
void display(int (&array)[rows][cols]) {
  int i, j;
  cout<<"\n";
  for(i = 0; i<rows; i++) {
      for(j = 0; j<cols; j++) {
        cout<<" ";
        cout<<array[i][j];
      }
      cout<<"\n";
    }
}


int main() {
  int M1[3][3];
  cout<<"Enter your matrix elements: \n";
  int i, j;
    for(i = 0; i<3; i++) {
      for(j = 0; j<3; j++) {
        cout<<"a["<<i<<"]["<<j<<"]: ";
        cin>>M1[i][j];
      }
    }
    display(M1);
  return 0;
}

是否可以在不使代码复杂化的情况下执行此类任务?

c++ matrix multidimensional-array
3个回答
1
投票

许多评论和评论都可以,但我认为最好的策略是使用单个矢量存储和形状矢量。学习蟒蛇numpy以理解概念或搜索ndarray,这是多少个不同的平台命名这个概念(n维数组)。然后,可以将捆绑数据向量,形状向量和方便的运算符和成员函数的类捆绑起来。


0
投票

经典答案需要您为阵列执行动态内存分配。如果你是新手,这有点压倒性。 (据我所知,这仍然是在C中完成的方法)

但是,在现代C ++中做类似事情的推荐方法是使用标准模板库。

/*
... Stuff where you get input from the user, specifically the num of rows and cols
... Say these vals were stored in 2 ints num_rows and num_cols
*/
std::vector<std::vector<int> > mat(num_rows);
for (int i = 0; i < num_rows; i++) {
    mat[i].resize(num_cols); // this will allow you to now just use [][] to access stuff
}

请参阅下面的第一条评论,它有一个很好的方法来避免循环设置向量并在初始化时处理它


-1
投票

您应该使用STL,但如果您更喜欢自己管理内存,那么这样的事情对您有用:

#include <iostream>
using namespace std;

template<typename T>
class Matrix
{
public:
    Matrix(unsigned nrows, unsigned ncols) 
        : m_nrows(nrows), m_ncols(ncols)
    {
        m_data = new T[m_nrows*m_ncols]();
    }
    ~Matrix()
    {
        delete[] m_data;
    }
    void setElement(unsigned row, unsigned col, const T elem)
    {
        m_data[(row - 1) * m_ncols + (col - 1)] = elem;
    }
    template<typename T>
    friend ostream& operator<<(ostream& os, const Matrix<T>& mat);
private:
    T* m_data;
    unsigned m_nrows;
    unsigned m_ncols;
};

template<typename T>
ostream& operator<<(ostream& os, const Matrix<T>& mat)
{
    for (unsigned i = 0; i < mat.m_nrows; i++)
    {
        for (unsigned j = 0; j < mat.m_ncols; j++)
        {
            cout << mat.m_data[i*mat.m_ncols + j] << " ";
        }
        cout << endl;
    }
    return os;
}

int main(int argc, char** argv) {
    if (argc < 3)
    {
        cout << "Usage: <program name> <num rows> <num cols>" << endl;
    }

    int nrows = atoi(argv[1]), ncols = atoi(argv[2]);
    Matrix<int> intMatrix(nrows, ncols);
    cout << intMatrix;

    // your code goes here
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.