[英]Initialize global array of function pointers at either compile-time, or run-time before main()
[英]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 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])
}
使用模板確實有缺點,模板必須出現在標題中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.