【发布时间】: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::array或std::vector。 -
#include <bits/stdc++.h>请不要那样做! -
数组,动态大小,带有指针之类的东西,即
std::vector。你为什么不想使用它? -
@idclev463035818 我现在正在学习C++,所以还不知道
std::vector的所有属性 -
c 数组超级复杂,向量很简单。习惯 c 数组有一定的价值,但是对于 C++ 的新手来说,没有理由更喜欢它们而不是向量