我知道这已经讨论过,并且有多个答案。例如,请参阅Performance of array of functions over if and switch statements,但我想得到一些其他的想法。
我有一个大型switch
声明的函数。这是26个case
,每个都有“左”或“右”选项。此函数返回基于两个给定参数(plane
和direction
)的指针:
double* getPointer(int plane, int direction) {
switch (plane)
{
case 0:
if (direction == 0)
return p_YZ_L; // Left
else if (dir == 1)
return p_YZ_R; //Right
else {
return 0;
}
break;
...
case 25:
...
}
}
同
planes -> [0-25]
direction -> [0,1]
我一直在考虑一系列功能,但这也可能很乏味,我不确定它是否是最好的选择。我还不清楚如何正确地做到这一点。有任何想法吗?
您可以像这样创建一个查找表:
double *pointers[26][2] = {
{ p_YZ_L, p_YZ_R },
...
};
然后你的功能变得更简单:
double* getPointer(int plane, int direction) {
if ((plane >= 0) && (plane < 26) && (direction >= 0) && (direction < 2)) {
return pointers[plane][direction];
} else {
return NULL;
}
}
如果你只是厌倦了打字,你可以使用预处理器,例如:
#define PLZ(dir) if(!dir)return(p_YZ_L);else if(dir==1)return(p_YZ_R);else return 0;
不太确定,但也许你想要这个:
struct
{
double dir[2];
} directions[26] =
{
{ p_YZ_L, p_YZ_R},
{ ..., ... }, // 25 pairs of options here
...
};
double* getPointer(int plane, int direction) {
return &directions[plane].dir[direction];
}
需要添加更多测试以确保plane
和direction
在必需的范围内。
您可以使用while与迭代器,如下所示:
double* getPointer(int plane, int direction){
int i=0;
while (i<26){
if (plane == i){
if (direction == 0)
return p_YZ_L; //Left
else if(dir==1)
return p_YZ_R; //Right
else
return 0;
}
i++;
}
}
它没有经过优化,但与您的版本相比,代码更少。