指向在编译时已知值的指针的指针数组

Array of pointers to pointers where values are known at compile-time

本文关键字:指针 数组 编译      更新时间:2023-10-16

我正在实现一个硬编码值的查找表,如果我能做这样的事情,那将是有用的:

double *table[rows];
table[0] = {1.0, 4.32};
table[1] = {2.0, 3.22};
重要的是它的类型必须是:double**

我目前的解决方案是有一个数组的数组,然后变成双**一行一次-但这是一个hack…

这个表需要传递给一个函数:

double NearestNeighbour(double** table, int width, int height, double key[]) 

其中widthheight为输入表的维数

你可以这样做

const double table2d[2][2] = 
{
  { 1.0, 4.32 },
  { 2.0, 3.22 }
};
const double *const table[2] = 
{
  table2d[0],
  table2d[1]
};

假设table2d声明为静态存储时间

由于c++ 11允许类类型的字面值,您可以使用具有返回double *的成员函数的字面值构建表:

#include <array>
double *table[] = 
{
    &std::array<double, 3>{ 1.0, 2.0, 3.0 }[0]
,   &std::array<double, 3>{ 4.0, 5.0, 6.0 }[0]
};

然而,这是相当丑陋的。特别是考虑到在调用NearestNeighbour时必须手动记住表宽度。

您现有的解决方案(或只构建一次表并保存它,并自动保留列数的版本)可能是最好的。


如果可能的话,看看是否可以修改NearestNeighbour。首先,如果它不修改表,那么它应该被写为取double const *const *table。然后你可以传递一个const表给它。

如果你可以访问它的源代码,那么你可以重新实现它作为一个模板函数来接受任何元素类型的数组,例如

template<typename RowT, size_t NumRows> 
double NearestNeighbour( RowT (&table)[NumRows], double *key )
{
    // here access table[row][col]
    // or even more generally, iterate over begin(table[row]), end(table[row])
}

使用模板的缺点是模板必须出现在标题中。