c++ - 矩阵 - 返回并作为参数传递 c++

标签 c++ matrix matrix-multiplication

我正在尝试使用清晰的函数对随机生成的值进行矩阵乘法。因此,我希望使用一个函数 (mat_def) 生成矩阵,并在将矩阵作为参数发送时使用另一个函数 (mat_mul) 将它们相乘。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

double mat_def(int n) //how to return the matrix
{
    double a[n][n];

    double f; 

    for(int i=0; i<n;  i++)
    {
        for(int j=0; j<n; j++)
        {
            f= rand();
            cout<<f ;
            a[i][j]=f;
        }

    }

    return 0;
}


double mat_mul( int n, double a[n][n], double b[n][n]) //how to send matrix as parameter
{
    return 0;
}


int main()
{
    /* initialize random seed: */
    srand (time(NULL));
    mat_def(10); 
}

最佳答案

这里有一个漂亮的标准 C++ 矩阵模板。

矩阵.h

#include <vector>

class Matrix
{
    class InnerM
    {
        private:
           int ydim;
           double* values;

        public:
            InnerM(int y) : ydim(y)
            {
                values = new double[y];
            }

            double& operator[](int y)
            {
                return values[y];
            }
    };

    private:
       int xdim;
       int ydim;

       std::vector<InnerM> inner;

    public:

       Matrix(int x, int y) : xdim(x), ydim(y), inner(xdim, InnerM(ydim))
       {
       }

       InnerM& operator[](int x)
       { 
           return inner[x];
       }
};

所有的内存泄漏都是为你准备的,但你明白了。在这里,您可以通过覆盖 Matrix 类中的 ::operator*() 来处理乘法。

关于c++ - 矩阵 - 返回并作为参数传递 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44550155/

相关文章:

c++ - 具有默认参数的类构造函数

c++ - Arduino 上一次中断的多个触发器

c++ - 如何使 SWIG 绑定(bind)类在 Lua 中使用运算符?

c++ - Allegro5 al_create_display() 在 Mac OS Catalina 上崩溃

c++ - 如何仅将矩阵的一维分配给 C++ 中的简单数组

java - 在更大的数组中移动 Java 数组

python - 如何使用 transformations.py 旋转一个点

c - 矩阵与线程相乘(每个线程做单次乘法)

java - 如何显示类(class)的结果?

c - 如何在C中对矩阵乘法进行计时?