你如何初始化一个二维数组,当你不知道的大小 [英] How do you initialize a 2 dimensional array when you do not know the size
问题描述
我有一个二维数组,我需要将数据加载到。我知道的数据(22值)的宽度,但我不知道的高度(约4000条记录估计,但变量)
I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable).
我把它声明如下:
float[,] _calibrationSet;
....
int calibrationRow = 0;
While (recordsToRead)
{
for (int i = 0; i < SensorCount; i++)
{
_calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat();
}
calibrationRow++;
}
这会导致一个NullReferenceException,所以当我尝试初始化像这样:
This causes a NullReferenceException, so when I try to initialize it like this:
_calibrationSet = new float[,];
我得到一个数组创建必须有数组大小或数组初始化程序。
I get an "Array creation must have array size or array initializer."
感谢您,
基思
Thank you, Keith
推荐答案
您不能使用数组。
或者说,你需要选择一个大小,如果你最终需要更多的,那么你就必须分配一个新的,更大的,数组,从旧的数据复制到新的,并继续像以前一样(直到你超越新一...的大小)
You can't use an array. Or rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...)
通常情况下,你会去的集合类之一 - ArrayList中,列表<>,LinkedList的< ;>,等等 - 哪一个很大程度上取决于你在找什么;名单会给你最接近我最初描述,而LinkedList的<>将避免频繁的重新分配问题(在较慢的访问和更大的内存使用量的费用)。
Generally, you would go with one of the collection classes - ArrayList, List<>, LinkedList<>, etc. - which one depends a lot on what you're looking for; List will give you the closest thing to what i described initially, while LinkedList<> will avoid the problem of frequent re-allocations (at the cost of slower access and greater memory usage).
例如:
List<float[]> _calibrationSet = new List<float[]>();
// ...
while (recordsToRead)
{
float[] record = new float[SensorCount];
for (int i = 0; i < SensorCount; i++)
{
record[i] = calibrationArrayView.ReadFloat();
}
_calibrationSet.Add(record);
}
// access later: _calibrationSet[record][sensor]
哦,这是值得注意的(如的 Grauenwolf 一样),这就是我在这里做不给你相同的内存结构单一,多维数组会 - 引擎盖下,它以实际保存数据的其他数组引用数组。这将加快通过再分配便宜构建阵列很划算,但可以有(当然和,内存使用情况)对访问速度产生影响。这是否是你的问题取决于你的数据它的加载后做了很多......以及是否有两百记录两万元的纪录。
Oh, and it's worth noting (as Grauenwolf did), that what i'm doing here doesn't give you the same memory structure as a single, multi-dimensional array would - under the hood, it's an array of references to other arrays that actually hold the data. This speeds up building the array a good deal by making reallocation cheaper, but can have an impact on access speed (and, of course, memory usage). Whether this is an issue for you depends a lot on what you'll be doing with the data after it's loaded... and whether there are two hundred records or two million records.
这篇关于你如何初始化一个二维数组,当你不知道的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!