【发布时间】:2021-12-24 20:21:59
【问题描述】:
我是 C++ 的新手,我在 python 中进行物理模拟,这需要很长时间才能完成,所以我决定切换到 C++,但我不明白如何创建一个返回 2D 数组的函数(或 3D 数组)
#include <iostream>
#include <cmath>
// #include <complex> //
using namespace std;
double** psiinit(int L, int n, double alpha){
double yj[400][400] = {};
for (int j = 0; j < n; j++)
{
double xi[400] = {};
for (int i = 0; i < n; i++)
{
xi[i] = exp(-(pow((i-(L/4)), 2) + (pow((j-(L/4)), 2)))/alpha) / (sqrt(2)*3.14159*alpha);
};
yj[j] = xi;
};
return yj;
}
int main(){
int L = 10;
int n = 400;
int nt = 200*n;
double alpha = 1;
double m = 1;
double hbar = 1;
double x[n] = {};
double y[n] = {};
double t[nt] = {};
double psi[nt][n][n] = {};
psi[0] = psiinit(L, n, alpha);
cout << psi <<endl;
return 0;
}
我一直在寻找答案,但似乎不是针对我的问题
谢谢
【问题讨论】:
-
创建一个代表二维数组的类。在该类中有一个线性
std::vector<double>并将 x,y 位置转换为线性向量。返回那个 2D 类。 -
你的数组是静态的,在栈上,只在
psiinit里面定义。所以你不能退货。以您的方式返回它会将地址返回到在函数末尾停止存在的东西。为什么不写好 C++ 并使用std::vector?你真的是在用 C++ 编写 C。 -
double [400][400]和double**是不相关的类型。 -
在建议的替代方案中:如果您仍然有固定大小,那么
std::array<std::array<double, Columns>, Rows>是不错的选择,您可以免费获得[row][column]索引 - 但请注意,在定义数组数组时,您必须颠倒列和行的顺序。这是标准委员会决定(不幸?)在模板参数中将类型置于大小之前的结果——向量的向量带有(隐藏的)双指针间接寻址,每个元素访问以及多个数组分配,所以线性向量(见@Eljay)更胜一筹。 -
您可能想要返回
std::vector<std::vector<double>>。或者,因为你在那里有固定的尺寸,所以用std::unique_ptr<std::array<std::array<double, 400>, 400>>使它更紧凑。使用(例如)auto yj = std::make_unique<std::array<std::array<double, 400>, 400>>();分配它,其余的应该很简单。您可以返回、传递和std::move和std::unique_ptr,它表示所有权并正确处理解除分配。对于范围受限的共享,您可以使用来自.get()的原始指针。对于线程安全的引用计数共享,请使用std::shared_ptr。
标签: c++ arrays multidimensional-array return