这是找到动态分配的数组长度的好方法吗? [英] Is this a good way to find the length of a dynamically allocated array?
问题描述
我有一个Matrix类,我想将一个数组传递给构造函数,以便动态设置矩阵的值.我发现如果分配这样的数组:
I have a Matrix class and I want to pass an array to the constructor in order to set the values of the matrix dynamically. I found that if I allocate an array like this:
double **array;
array = new double*[3];
array[0] = new double[2];
array[1] = new double[2];
array[2] = new double[2];
array[0][0] = 1;
array[0][1] = 1;
array[1][0] = 1;
array[1][1] = 1;
array[2][0] = 1;
array[2][1] = 1;
我可以使用如下方法获取行数和列数:
I can get the number of rows and cols using a method like this:
int getNRows(double **data){
int size = 0;
while(*(data+size)){size++;}
return size;
}
int getNCols(double **data){
int size = 0;
while(**(data+size)){size++;}
return size;
}
这样可以吗,还是应该坚持使用向量声明?
Is this ok or should I stick to the vector declaration?
推荐答案
您的假设完全错误;您无法以接近您建议的任何方式获得尺寸.这是完全不确定的危险行为.
Your assumption is totally wrong; you cannot obtain the size in any way close to what you propose. That's utterly undefined and dangerous behaviour.
这是伪规则(即不正确,但是除非您理解为什么不正确,否则它适用于您):
Here's a pseudo-rule (i.e. it's not true, but unless you understand why it's not true, it applies to you):
不要使用指针.不要使用new
和delete
. (不要说using namespace std;
.)
Don't use pointers. Don't use new
and delete
. (And don't say using namespace std;
.)
使用C ++容器是唯一的方法.
The one and only way in which you should be doing this is with C++ containers.
向量的向量将是第一个镜头,尽管跨步访问的平面向量可能会更好,并且Boost.multi_array甚至可能是最好的:
A vector of vectors would be the first shot, though a flat vector accessed in strides may be better, and Boost.multi_array may even be the best:
-
std::vector< std::vector<double> > v (3, std::vector<double>(2));
std::array<std::array<double, 2>, 3>
std::vector<double> v(6);
,并使用v[i + 2 *j]
等.
这篇关于这是找到动态分配的数组长度的好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!