【问题标题】:Better alternatives for switch statementsswitch 语句的更好替代方案
【发布时间】:2016-11-04 15:46:25
【问题描述】:

我知道这已经讨论过了,并且有多个答案。例如,请参阅Performance of array of functions over if and switch statements,但我想了解其他一些想法。

我有一个带有大 switch 语句的函数。这是 26 个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] 

我一直在考虑一系列函数,但这也可能很乏味,我不确定它是否是最佳选择。我也不清楚如何正确地做到这一点。有什么想法吗?

【问题讨论】:

  • 请出示您所说的包含switch语句的代码。
  • 假设左右子案例不共享太多代码,具有 26 个开关案例的两个函数可能是一个不错的选择。
  • 数组double* x[2][26]return x[direction][plane]怎么样?
  • @MichaelWalz 这只显示了一个大的switch,每个if else 内都有case
  • 我对此有点晚了,但与其使用双精度数组,不如使用带标志的无符号 32 位整数。其中第 0 位是方向,第 1-26 位使用标志指示平面。我说飞机是因为它可以使编队运动〜0(全部向右移动)和〜1(全部向左移动)......您还可以为向上/向下保留额外的位(或者更合适的俯仰,偏航和滚动)。

标签: c


【解决方案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;
    }
}

【讨论】:

  • @_dbush 这不应该是direction &lt; 2 吗?
  • @Manolete 是的,应该。已编辑。
【解决方案2】:

如果你只是打字累了,你可以使用预处理器,例如:

#define PLZ(dir) if(!dir)return(p_YZ_L);else if(dir==1)return(p_YZ_R);else return 0;

【讨论】:

    【解决方案3】:

    不太确定,但也许你想要这个:

    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 在要求的范围内。

    【讨论】:

      【解决方案4】:

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

      它没有经过优化,但相对于您的版本而言代码更少。

      【讨论】:

      • @_reshad 我同意,它的代码更少,但不是我所追求的
      猜你喜欢
      • 2011-01-19
      • 2022-11-22
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 2017-06-01
      • 1970-01-01
      相关资源
      最近更新 更多