将直方图的 2D 数组传递给函数 (C++)?
Pass 2D array of histograms to function (C++)?
在ROOT(欧洲核子研究中心语言(的C++中,我声明了一个直方图的二维数组:
TH1F *hist[xlen][ylen];
其中xlen
和ylen
不是可变长度的;我在代码中为它们分配值。
我想将此 2D 数组传递到一个函数中。但是,我在指定输入参数时遇到问题。有人可以帮助我吗?
例如,我可以传递一个一维直方图(TH1F *hist[length];
(,函数如下:
void func(TH1F** Hist) {
cout<<Hist[0]<<endl;
}
请注意,虽然我的 2D 直方图有一个确定的大小(即xlen
,ylen
(,正如我的代码中所定义的那样,我不希望该函数仅限于单个大小的数组。
如果你想对同一个程序中的不同维度使用相同的函数,我看到的唯一方法是将指向数组第一个元素的指针与维度一起传递,然后自己计算每个索引,即通过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 数组。
斯蒂芬的答案似乎最接近按预期解决它,但没有奏效。对我来说,知道如何调整代码以使其工作也有点太复杂了。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗