【问题标题】:Dynamic array size to calculate the determinant of a matrix动态数组大小来计算矩阵的行列式
【发布时间】:2020-09-09 19:28:16
【问题描述】:

基本上,我已经编写了一个程序来计算矩阵的行列式。

但是,这感觉还很静态(即维度作为参数传递)。有什么方法可以让它更动态(没有vectors)用指针之类的东西?

#include <bits/stdc++.h> 
using namespace std; 

#define N 4 

void getCofactor(int mat[N][N], int temp[N][N], int p, int q, int n) 
{ 
    int i = 0, j = 0; 

    for (int row = 0; row < n; row++) 
    { 
        for (int col = 0; col < n; col++) 
        { 
            if (row != p && col != q) 
            { 
                temp[i][j++] = mat[row][col]; 
  
                if (j == n - 1) 
                { 
                    j = 0; 
                    i++; 
                } 
            } 
        } 
    } 
} 
  
int determinantOfMatrix(int mat[N][N], int n) 
{ 
    int D = 0;
  
    if (n == 1) 
        return mat[0][0]; 
  
    int temp[N][N];  
    int sign = 1; 
  
    for (int f = 0; f < n; f++) 
    { 
        getCofactor(mat, temp, 0, f, n); 
        D += sign * mat[0][f] * determinantOfMatrix(temp, n - 1); 
  
        sign = -sign; 
    } 
  
    return D; 
} 

【问题讨论】:

  • 简短回答 - 不。您无法从指向数组的原始指针获取数组的大小,因此您必须将大小作为参数传递,或者使用带有自己大小的容器,如 std::arraystd::vector
  • #include &lt;bits/stdc++.h&gt; 请不要那样做!
  • 数组,动态大小,带有指针之类的东西,即std::vector。你为什么不想使用它?
  • @idclev463035818 我现在正在学习C++,所以还不知道std::vector的所有属性
  • c 数组超级复杂,向量很简单。习惯 c 数组有一定的价值,但是对于 C++ 的新手来说,没有理由更喜欢它们而不是向量

标签: c++ function pointers


【解决方案1】:

无法将指针传递给动态大小的数组。而且数组的内部维度无论如何都不能是动态的。

您可以做的是使用一维动态数组,像往常一样传递指向该数组元素的指针,并一个接一个地存储行,并根据作为数组传递的行大小计算索引。这会产生与数组数组相同的布局,但“虚拟”维度可以是动态的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-31
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    • 2015-01-16
    相关资源
    最近更新 更多