最简单的二维数组,使用G ++,有一个可变尺寸的? [英] Simplest 2D array, using g++, with one variable dimension?
本文介绍了最简单的二维数组,使用G ++,有一个可变尺寸的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想作一个这样的数组:
I would like to make an array like this:
double array[variable][constant];
只有第一尺寸是可变的。一个变量声明这是第一个维度给出了初始化错误。有没有一种简单的方法来使用指针或其他基本类型做到这一点?
Only the first dimension is variable. Declaring this with a variable as the first dimension gives initialization errors. Is there a simple way to do this with pointers or other basic types?
推荐答案
您可以做这样的事情,但它不是一个真正的二维数组。它是基于内部一个多维数组必然与规则线性的总体思路,对尺寸(N,M),你有一个数组: array2d [I,J] = array1d [J +我* M]
You could do something like that, but it is not a true 2D array. It is based on the general idea that internally a multiple dimension array is necessarily linear with the rule that for an array of dimensions (n, m) you have : array2d[i, j] = array1d[j + i*m]
#include "iostream"
using namespace std;
class dynArray {
private:
double *array;
int dim2;
public:
dynArray(int variable, int constant) {
array = new double[variable * constant];
dim2 = constant;
}
~dynArray() {
delete array;
}
double value(int i, int j) {
return array[j + i * dim2];
}
double *pt(int i, int j) {
return array + j + i * dim2;
}
};
int main(int argc, char*argv[]) {
dynArray d(3,4);
*d.pt(2,3) = 6.;
cout << "Result : " << d.value(2,3) << endl;
return 0;
}
这篇关于最简单的二维数组,使用G ++,有一个可变尺寸的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文