获取实际填充 N x M 数组数据的行数和列数
我正在用 Delphi 编写一些矩阵例程,出现了这个问题。我这样定义了一个实数矩阵:-
RealArrayNPbyNP = Array[1..200,1..200] of Extended;
我用 5 x 6 矩阵填充了这个数组。
如何查询数组以获取 delphi 代码中的行数(在本例中为 5)和列数(在本例中为 6)。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您将矩阵声明为 200 x 200。无论您使用多少,矩阵始终为 200 x 200。5 x 6 范围之外的所有字段都至少包含一些数据,无论有用还是无用。
也许您应该考虑使用动态数组:
这样您就可以使用 Setlength 来使数组尺寸适合您的需要。要获得 5x6 矩阵,您可以使用以下代码(感谢 Rob 的提示):
如您所见,可以使用 Length 函数查询实际尺寸。 Length(arr) 获取第一个维度,而 Length(arr[I) 将给出第二个维度。
通过这种构造,矩阵的每个“行”都可以具有独立数量的“列”。
You declared the matrix as 200 x 200. No matter how much of it you use, the matrix is always 200 x 200. All fields outside of your 5 x 6 range contain at least some data, be it useful or not.
Perhaps you should consider using dynamic arrays:
With this you can use Setlength to fit the array dimensions to your needs. To get a 5x6 matrix you can use this code (thanks to Rob for the hint):
As you can see, the actual dimension can be queried with the Length function. Length(arr) gets the first dimension while Length(arr[I) will give the second dimension.
With this construct each "row" of the matrix can have an independent number of "columns".
如果您不需要动态数组并且没有关于哪些值构成有效值的附加信息(即,如果您无法搜索它们/对它们进行计数),那么您基本上必须拥有附加信息。换句话说,您还需要两个变量:
NRows
和NColumns
,您在填充数组时设置它们。If you don't want a dynamic array and have no additional information as to which values constitute valid ones (i.e., if you can't search for them/count them), you'll essentially have to have additional information. In other words, you'd need two more variables,
NRows
andNColumns
which you set when you populate the array.如果您可以保证矩阵最初填充的是已知值,例如 0 或某个无效值,那么您可以执行相当于
strlen()
的操作,并简单地计算第一行中的元素数量和出现在标志值之前的列。然而,这往往效率低下。为什么不能根据需要传递当前大小?或者更好的是,将矩阵功能封装在适当的对象中。If you can guarantee that the matrix is initially populated with known values, e.g., 0 or some invalid value, then you can do what amounts to
strlen()
and simply count the number of elements in the first row and column that are present before the flag value. This tends to be inefficient, however. Why can't you just pass the current size around as you need it? Or better yet, encapsulate your matrix functionality in a proper object.如果我正确理解你的问题,你想要做的是拥有一个预先分配的数组,你只填充了部分数组,并且你想要确定填充了多少。
我将创建一个包含处理此“数组”的所有逻辑的类,并为包含以下逻辑的数组编写一个属性设置器:
以及一个如下所示的数组初始化/清除函数:
您还可以扩展通过添加与布尔值边界匹配的另一个数组并对其进行适当修改来确定数组元素是否具有值。
If I understand your problem correctly, what your trying to do is to have a preallocated array, which you are only filling partially and your wanting to determine how much is filled.
I would create a class which contains all of the logic for dealing with this "array" and write a property setter for the array which contained the following logic:
and an array initialization/clear function which looked like the following:
You can also extend the determination of if an array element has a value by adding another array which matches the bounds of boolean and modifying it appropriately.