2013-02-06 93 views
-1

我整理我的字符串(升序)使用switch-case而不是「if」會好嗎?

Sorted string : ! % & * + , -/; <=> ?^| ~ 
33, 37, 38, 42, 43, 44, 45, 47, 59, 60, 61, 62, 63, 94, 124, 126 

這是很多運營商。目前我正在使用if語句。我是否應該爲此案申請開關櫃?它會影響速度&的性能?哪個更好?

一些例子:

case 47 : 
case 59 : //Does it affect performance? 

在我看來,它應該是:

case 1 : 
case 2 : 
case 3 : 
etc 
+0

這是什麼語言?請給出更多的上下文。 –

+0

多個ifs可以被開關替換 – Satya

回答

6

我不會擔心性能,而是可讀性。
您只能在基本類型上使用switch語句(如int,char,enums等)。
編譯器很可能會優化兩個決定之間的等價關係,只要它們具有相同的行爲。

此外,只是因爲字符在ASCII表中表示爲整數,並不意味着您應該在字符開關的case語句中使用整數。

char c = '%'; 
    switch(c){ 
     case '!': 
      //... code ... 
      break; 

     case '%': 
      //... code ... 
      break; 

     case '&': 
      //...code ... 
      break; 

     //etc ... 
    } 
6

此之前已經問在計算器上:

而且還對其他論壇:


如果使用的字符執行下列操作

它要求之前,建議Google


感謝Xploit,我一直在提醒,您也可以直接放在char s轉換爲switch語句,因爲所有的一個char是,是一個整數。

case '*':case 42:相比,哪一個更容易閱讀?

+0

我使用Google搜索,但找不到正確的答案。這是關於整數和整數。「 – xersi

+0

」switch語句只能用[有序值](https://en.wikipedia.org/wiki/Ordinal_number) - 即整數。因此,如果您想使用具有非整數值的開關,您必須有某種方法將該值轉換爲整數。「 - [CPlusPlus.com](http://www.cplusplus.com/faq/sequences/strings/switch-on-string/)。所以沒關係,與開關有關的任何事情仍然是關於整數。 – question

1

你也可以實現使用一個表,在升級軟件時,這可能是更少的工作:

typedef void (*Ptr_Processing_Function)(char token); 

struct Table_Entry 
{ 
    char      token_char; 
    Ptr_Processing_Function process_token; 
}; 


static const Table_Entry operators_table[] = 
{ 
    {'+', Process_Plus_Operator}, 
    {'-', Process_Minus_Operator}, 
    //... 
}; 
static const unsigned int OPERATOR_QUANTITY = 
    sizeof(operators_table)/sizeof(operators_table[0]); 

void Process_Token(char token) 
{ 
    bool token_found = false; 
    for (unsigned int i = 0; i < OPERATOR_QUANTITY; ++i) 
    { 
     if (token == operators_table[i].token_char) 
     { 
      if (operators_table[i].process_token != NULL) 
      { 
       process_token(token); 
       token_found = true; 
       break; 
      } 
     } 
    } 
} 

異常情況作爲練習留給讀者。

相關問題