繁体   English   中英

切换语句的更好替代方案

[英]Better alternatives for switch statements

我知道这已经讨论过,并且有多个答案。 例如,请参阅if和switch语句的函数数组的性能 ,但是我想得到一些其他的想法。

我有一个带有大型switch语句的函数。 这是26个case ,每个case都有“左”或“右”选项。 此函数根据两个给定参数( planedirection )返回指针:

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];
}

需要添加更多测试以确保planedirection在所需的范围内。

您可以使用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++;
  }
}

它没有经过优化,但与您的版本相比,代码更少。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM