矩阵-返回并作为参数c ++传递 [英] Matrix - return and pass as parameter c++

查看:102
本文介绍了矩阵-返回并作为参数c ++传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use clear functions to do a matrix multiplication with random generated values. Therefore I'm hoping to use a function(mat_def) to generate the matrices and another function(mat_mul) to multiply them when the matrices are sent as parameters.

#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 ++矩阵模板.

Here's a nice, standard C++ Matrix template for you.

Matrix.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*()来处理乘法.

All the memory leaks are there for you but you get the idea. From here you can handle the multiplication by overiding ::operator*() in the Matrix class.

这篇关于矩阵-返回并作为参数c ++传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆