2012-04-16 34 views
1

例如,我的情況:
我收到「0」,「1」,「true」或「false」的輸入。 (無論如何)
什麼是最好的性能,代碼讀取方面,任何基本最佳實踐:正在使用std :: regex進行簡單的RX是很好的做法嗎?

bool func(string param) 
{ 
    string lowerCase = param; 
    to_lower(lowerCase); 
    if (lowerCase == "0" || lowerCase == "false") 
    { 
     return false; 
    } 
    if (lowerCase == "1" || lowerCase == "true") 
    { 
     return true; 
    } 
    throw .... 
} 

或:

bool func(string param) 
{ 
    string lowerCase = param; 
    to_lower(lowerCase); 
    regex rxTrue ("1|true"); 
    regex rxFalse ("0|false"); 

    if (regex_match(lowerCase, rxTrue) 
    { 
     return true; 
    } 
    if (regex_match(lowerCase, rxFalse) 
    { 
     return false; 
    } 
    throw .... 
} 
+2

對於正則表達式,應該有一個標誌,告訴它不區分大小寫,所以你不必將其轉換爲小寫。除此之外,我認爲明確的檢查更明確,更易於閱讀, – 2012-04-16 07:27:13

回答

3

第二是更爲清楚,並更容易延伸(例如:接受 "yes""no",或前綴,與"1|t(?:rue)?)""0|f(?:alse)?"與性能有關的,所述第二可(和 應該)顯著更快通過由聲明regexstatic (和const,而你在它),例如:

static regex const rxTrue ("1|true" , regex_constants::icase); 
static regex const rxFalse("0|false", regex_constants::icase); 

還要注意通過指定不區分大小寫,你就不必 轉換輸入爲小寫。

1

這只是一種預感,但可能是第一個將會更快(不涉及正則表達式編譯)。此外,第二個版本取決於您的編譯器支持C++ 11 <regex>實現,因此根據您需要支持的環境,第二個選項會自動排除。

相關問題