gpt4 book ai didi

c++ - 将数组传递给 C++ 中的函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:57:29 26 4
gpt4 key购买 nike

我想将数组传递给 C++ 中的某个函数。我写了下面的代码:

#define nmpart 50

void distances( double (&dis)[3][nmpart][nmpart] )
{
... compute distances which are allocated in "dis"
}

double energy()
{
double dis[3][nmpart][nmpart];

distances(dis);
}

当 nmpart<800 左右时,这段代码工作正常。问题是我想要有一个更大的数组,假设 nmpart=50000。我在这个论坛上读到那个可以使用动态分配来克服这个问题。我不清楚怎么会我在这种情况下使用动态分配。你能给我一些提示吗?

最佳答案

现在,很多人(包括我自己)永远不会以专业(或其他方式)编写这段代码,但它基本上回答了你的问题。请参阅下文,了解为什么我永远不会专业地写这篇文章。

#define nmpart 50  

void distances( const double ***dist)
{
... compute distances which are allocated in "dis"
}

double energy()
{
double ***dis;

// allocate dis
dis = new double**[3];
for(int i=0;i<3;++i)
{
dis[i] = new double*[nmpart];
for(int j=0;j<nmpart;++j)
{
dis[i][j] = new double[nmpart];
}
}

// code where you populate dis
// HERE

distances(dis);

// deallocate dis
for(int i=0;i<3;++i)
{
for(int j=0;j<nmpart;++j)
{
delete [] dis[i][j];
}
delete [] dis[i];
}
delete [] dis;

}

基本上,我永远不会写这个(除非是出于教学目的),因为如果在这个函数的某处抛出异常,那么它就会泄漏内存。最好的办法是将堆分配和释放(分别使用 newdelete)包装在一个类中,然后将该类放在 energy() 内的本地堆栈上。功能。

理想情况下你会做这样的事情:

#define nmpart 50    

void distances( const distClass &dis)
{
... compute distances which are allocated in "dis"
}

double energy()
{
distClass dis;
// this allocate wraps the for loops with the new []'s above
dis.Allocate(3, nmpart , nmpart);

// populate dis HERE

distances(dis);

// when dis goes out of scope its destructor
// is called, which wraps the for loops with the delete []'s
}

关于c++ - 将数组传递给 C++ 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7748195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com