简体   繁体   English

指向2或3维子数组/子矩阵的指针

[英]Pointer to 2 or 3 dimensional sub-array/sub-matrix

say you have a matrix of dimensions x per y (per z) defined like: 假设您有一个尺寸为x / y(每个z)的矩阵,定义如下:

int** tab = new int*[x];
for(int i=0; i<x; ++i) tab[i] = new int[y];

or 要么

int*** tab = new int**[x];
for(int i=0; i<x; ++i) {
  tab[i] = new int*[y];
  for(int j=0; j<y; ++y) tab[i][j] = new int[z];
}

is there any smart way to access sub-matrix (get int**(*) without data copying, plain C++) which will have top-left(-front) corner [a,b(,c)] and size of [A, B(,C)]? 是否有任何智能方法可以访问子矩阵(无需复制数据即可获取int**(*) ,普通C ++),该子矩阵的左上角(-front)角为[a,b(,c)],大小为[A ,B(,C)]?

Here are (better or worse) graphical examples of the problem. 这是问题的(更好或更坏的)图形示例。

矩阵二维示例 在此处输入图片说明

You are using what is called a jagged array. 您正在使用所谓的锯齿状数组。 It is an array of arrays, where nothing besides runtime enforces that the sub arrays are the same size. 它是一个数组数组,其中除了运行时以外,所有其他内容都不要求子数组的大小相同。 Hence jagged, because you could have the subarrays vary in size. 因此参差不齐,因为您可能会使子数组的大小不同。

In order to have a submatrix that is also a jagged array, you need for there to exist a jagged array of pointers pointing at the subarrays of the submatrix. 为了使子矩阵也是锯齿状的数组,您需要存在一个指向子矩阵的子数组的指针的锯齿状数组。 These don't exist in general, so no, you cannot do this "without copying" at least some arrays of pointers to subarrays. 这些通常不存在,所以不,您不能“不复制”至少某些指向子数组的指针数组。

Had your matrix been not jagged array based, but instead single array with stride , then views of subarrays could be created without allocating new subarray pointer arrays. 如果您的矩阵不是基于锯齿状的数组,而是具有stride的单个数组,则可以在不分配新的子数组指针数组的情况下创建子数组的视图。 Also it would be more cache friendly. 同样,它对缓存更友好。

To write the non-jagged matrix, start by writing an array view or span class that handles one dimension. 要编写非锯齿状的矩阵,请先编写一个处理一维的数组视图或span类。

For two dimensions, you augment the span class to store a tuple of dimension sizes or strides. 对于两个维度,您可以扩展跨度类以存储维度大小或跨度的元组。 [] instead of returning a reference to the calculated element, creates a one-dimension-lower span instance pointing at the calculated position, until the dimension 0 case where you return a reference. []而不是返回对计算元素的引用,而是创建一个一维低跨度的实例,该实例指向计算位置,直到维度0的情况下返回引用。

This will be highly efficient, permit efficient subarrays, but requires a few dozen or 100 lines of code to get right. 这将是高效的,允许高效的子数组,但是需要几十行或100行代码才能正确执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM