指向在编译时已知值的指针的指针数组
Array of pointers to pointers where values are known at compile-time
我正在实现一个硬编码值的查找表,如果我能做这样的事情,那将是有用的:
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[])
其中width
和height
为输入表的维数
你可以这样做
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])
}
使用模板的缺点是模板必须出现在标题中。
相关文章:
- 指向指向字符数组的指针数组的指针
- 通过指向指针数组的指针访问子类的属性
- C++,指针数组,指向双链表中的条目
- 在C++中,如何初始化指向wchar_t*的指针数组(生成wchar_t**)
- C++从函数指针数组调用函数
- 关于指向指针数组的指针
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 将链表转换为指针数组时出错
- C++ 对象指针数组的复制构造函数
- C++ - 循环访问指针数组会导致错误
- 删除指针数组 (C++) 中的元素
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 将函数指针数组中的函数指针作为模板参数传递
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 具有推导参数的模板函数指针数组变量
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- C++指针数组到字符数组中的特定位置
- 如何在C++中复制指针数组的数据
- 初始化类中的指针数组,并在另一个类中检索它
- 尽管直接设置了指针数组,但仍为空