【问题标题】:How to call a dynamic matrix into a function?如何将动态矩阵调用为函数?
【发布时间】:2017-11-08 18:16:25
【问题描述】:

我已经这样声明了一个矩阵:

double **MB;
    MB = new double *[650000];
     for (int count = 0; count < 650000; count++)
     MB[count] = new double [2];

现在我想在一个应该修改它的函数中调用我的矩阵。

bool notindic (..., double MB [][2], ...) {}

主要是:

notindic(..., MB, ...)

现在它给了我这个错误: *[Error] cannot convert 'double**' to 'double ()[2]' for argument '3' to 'bool notindic(std::string, std: :string, double ()[2], int, int)'

我该如何解决?

谢谢。

【问题讨论】:

  • 您将动态分配的数组与静态数组混合在一起。编译器没有可用的信息表明 MB 是一个数组。就它而言,它只是一个双**。所以你应该改变 notindic 来接受一个 double** 参数。

标签: c++ matrix memory dynamic


【解决方案1】:

只需将数组指针作为参数传递

#include <iostream>


const int NX = 65;
const int NY = 2;

bool notindic(double** MB) {
        for(int i = 0; i < NX; ++i) {
                for(int j = 0; j < NY; ++j) {
                        MB[i][j] = i + j;
                }
        }
}

int main() {
        double **MB = new double *[650000];
        for (int count = 0; count < 650000; count++) {
                MB[count] = new double [2];
        }

        notindic(MB);

        for(int i = 0; i < NX; ++i) {
                for(int j = 0; j < NY; ++j) {
                        std::cout << MB[i][j] << " ";
                }
                std::cout << std::endl;
        }
}

【讨论】:

    【解决方案2】:

    忘记所有那些指针的废话。它容易出错、异常不安全、难以编写、难以阅读、难以维护并且可能表现不佳。将您的矩阵表示为 std::vector&lt;double&gt; 并相应地计算偏移量。

    bool notindic (std::vector<double> const& matrix, int m) {
        // ...
        auto const element = matrix[y * m + x];
        // ...
    }
    
    auto const m = 650000;
    auto const n = 2;
    std::vector<double> my_matrix(m * n);
    auto const result = notindic(my_matrix, m);
    

    当您使用它时,将其包装在这样的类中:

    template <class T>
    class Matrix final
    {
    public:
        Matrix(int m, int n) :
            data(m * n),
            m(m)
       {
       }
    
       T& operator()(int x, int y)
       {
           return data[y * m + x];
       }
    
       T const& operator()(int x, int y) const
       {
           return data[y * m + x];
       }
    
    private:
        std::vector<T> data;
        int m;
    };
    
    bool notindic (Matrix<double> const& matrix) {
        // ...
        auto const element = matrix(x, y);
        // ...
    }
    
    auto const m = 650000;
    auto const n = 2;
    Matrix<double> my_matrix(m, n);
    auto const result = notindic(my_matrix);
    

    如果需要,添加其他成员函数。

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 1970-01-01
      • 2017-08-02
      • 2015-06-02
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多