创建N维数组,其中N在运行时确定(C ++) [英] Create an N dimensional array, where N is determined at runtime (C++)

查看:147
本文介绍了创建N维数组,其中N在运行时确定(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将N-Dim图像立方体编码为不同的图像格式。我不知道图像的尺寸,直到运行时和我用来从原始图像读取的库需要一个N-dim数组目标缓冲区作为参数。

I'm encoding N-Dim image cubes into a different image format. I don't know the dimensions of the image until runtime and the library I'm using to read from the original image needs an N-dim array destination buffer as a parameter.

如何在C ++中声明这样的数组?谢谢:)

How can I declare such an array in C++? Thanks :)

推荐答案

简短的答案是,你不能在C ++中声明这样的数组。数组的维度是类型的一部分(对于 extern 一个 >数组声明)。维度的数量始终是类型的一部分,并且类型必须在编译时已知。

The short answer is that you cannot declare such an array in C++. The dimensions of an array are part of the type (with a miscellaneous exception that sometimes the value of one of the dimensions can be unknown, for an extern array declaration). The number of dimensions is always part of the type, and the type must be known at compile time.

您可以做的是使用flat 数组的大小合适。例如,如果你需要一个3x3 ... x3数组,那么你可以在运行时计算 3 ^ n ,动态分配许多 int (为了方便起见,可能使用向量< int> ),并且你有一个与 int [3] 3] ... [3] 。你可以通过 void * 来引用这个内存。

What you might be able to do instead is to use a "flat" array of appropriate size. For example, if you need a 3x3...x3 array then you can compute 3^n at runtime, dynamically allocate that many int (probably using a vector<int> for convenience), and you have memory with the same layout as an int[3][3]...[3]. You can refer to this memory via a void*.

我不确定它在C ++以将平面数组别名为多维数组。但首先,你调用的函数可能不会实际上别名,无论如何,鉴于它也不知道在编译时的维度。其次,它会在实践中工作(如果没有,你调用的函数被破坏,或者有一些狡猾的方法来处理这个,你应该找出并复制)。

I'm not certain that it's strictly legal in C++ to alias a flat array as a multi-dimensional array. But firstly the function you're calling might not actually alias it that way anyway given that it also doesn't know the dimension at compile-time. Secondly it will work in practice (if it doesn't, the function you're calling is either broken or else has some cunning way to deal with this that you should find out about and copy).

这篇关于创建N维数组,其中N在运行时确定(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆