将直方图的 2D 数组传递给函数 (C++)?

Pass 2D array of histograms to function (C++)?

本文关键字:函数 C++ 直方图 2D 数组      更新时间:2023-10-16

在ROOT(欧洲核子研究中心语言(的C++中,我声明了一个直方图的二维数组:

TH1F *hist[xlen][ylen];

其中xlenylen不是可变长度的;我在代码中为它们分配值。

我想将此 2D 数组传递到一个函数中。但是,我在指定输入参数时遇到问题。有人可以帮助我吗?

例如,我可以传递一个一维直方图(TH1F *hist[length];(,函数如下:

void func(TH1F** Hist) {
cout<<Hist[0]<<endl;
}

请注意,虽然我的 2D 直方图有一个确定的大小(即xlenylen(,正如我的代码中所定义的那样,我不希望该函数仅限于单个大小的数组。

如果你想对同一个程序中的不同维度使用相同的函数,我看到的唯一方法是将指向数组第一个元素的指针与维度一起传递,然后自己计算每个索引,即通过current_row_index * column_size + current_column_index

void func(int rows, int columns, int **hist) {
static int arr[10] = {0,1,2,3,4,5,6,7,8,9};
for(int r=0; r<rows; r++) {
for(int c=0; c<columns; c++) {
int* aPtr = &arr[(r*columns+c)%10];
hist[r*columns + c] = aPtr;
cout << *hist[r*columns + c] << " ";
}
cout << endl;
}
}
int main() {

int *a20x10[20][10] = {};
int *a5x3[5][3] = {};
func(20,10,&a20x10[0][0]);
func(5,3,&a5x3[0][0]);
return 0;
}
/*But first of all you want to pass by reference, so a 
* more correct function call might be:
*/
void Call(TH1F **Hist, size_t size_x, size_t size_y);
/* allows changing hist or setting to NULL
* in function
*/
void Call2(TH1F ***Hist, size_t size_x, size_t size_y);
/* with a call like */
int main(void)
{
TH1F *hist[xlen][ylen] = NULL;
/* malloc here/memset hist */
Call(*hist, xlen, ylen);
Call2(hist, xlen, ylen);
return (0);
}

您可以使用模板函数执行此操作。模板将自动选取数组的维度。

template<int C, int R>
void func(TH1F* (&hist)[C][R])
{
cout << hist[0][0] << endl;
}

我设法通过规避这个问题来让它正常工作:使用向量的向量而不是 2D 数组。

斯蒂芬的答案似乎最接近按预期解决它,但没有奏效。对我来说,知道如何调整代码以使其工作也有点太复杂了。