当数组的维数是输入变量时如何声明数组 [英] how to declare an array when the dimension of the array is an input variable

查看:98
本文介绍了当数组的维数是输入变量时如何声明数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想声明一个数组z [m] [n],m = 100,n是对话框中的输入变量,我使用此方法:

I want to declare an array z[m][n], m=100,n is an input variable from the dialog box, I use this method:

double **z = new double *[m];
for (i=0;i<m;i++)
{
   z[i]=new double [n];
}
///////////
///////////

for (i=0;i<m;i++)
{
   delete []z[i];
}
delete []z;


有没有更好的方法来声明这样的数组?
谢谢.


is there a better way to declare such an array?
thank you.

推荐答案

有什么更好的办法?
另一种方式可以是
what can be better?
another way can be
//i am not saying this is a better way
double *z=new double[m * n]; //then accessing will be tricky
for (int i=0;i<m;i++);
{
 for (int j=0;j<n;j++);
 {
  desired_value=z[i*m+j];
 }
}
delete[] z;//at least in delete you wont have to loop through;


您始终可以使用许多可用的容器类之一(CArray,vector,array等).它们是否是更好的选择? ...取决于您的使用.

例如,在有连续分配的情况下,std :: vector往往会具有更好的性能……因为对此进行了优化(通过预分配内存).如果多维数组分配一次并且变化不大,则分配性能差异实际上可以忽略不计.阅读您的选择并下定决心.

祝你好运!

一些参考:
http://www.cplusplus.com/reference/stl/vector/ [ http://www.cplusplus.com/reference/stl/array/ [ http://msdn.microsoft.com/en-us/library/4h2f09ct (v = VS.80).aspx [
You can always use one of the many container classes available (CArray, vector, array, etc...). Whether they are better options? ...depends on your use.

For example, std::vector tends to have better performance in the case when there are continual allocations... because it''s been optimized for that (by pre-allocating memory). If your multi-dimensional array is allocated once and doesn''t change much, the allocation performance difference is really negligible in comparison. Read up on your options and make up your own mind.

Good luck!

Some references:
http://www.cplusplus.com/reference/stl/vector/[^]
http://www.cplusplus.com/reference/stl/array/[^]
http://msdn.microsoft.com/en-us/library/4h2f09ct(v=VS.80).aspx[^]


//C ++,MFC
您也可以尝试实现以下类:):
// C++, MFC
You could also try to implement the following class :) :
typedef CArray<double> CRowData;
typedef CArray<CRowData> CDblMtx;

class CDblMatrix : private CDblMtx
{
  CSize m_sizeDimensions;

public:
  CDblMatrix(int iRows, int iCols);
  virtual ~CDblMatrix();

  void SetSize(const CSize& cNewSize);
  const CSize& GetSize() const;

  void SetAt(int iRow, int iCol, const double& dVal);
  const double& GetAt(int iRow, int iCol) const;
};


这篇关于当数组的维数是输入变量时如何声明数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆