2012-10-28 82 views
4

我在寫一個函數,它以字符串的形式讀取後綴表達式並相應地計算它。如何將'+'轉換爲+,'*'爲*等

是否有一種簡單的方法將算術運算符的字符轉換爲C++中的算術運算符本身?

+7

根據您支持的操作符的數量,您可能希望將每個字符映射到函數,如'std :: plus'。 – chris

+0

我支持'+',' - ','*'和'/'。 –

回答

9

假設這是對經典的RPN編程鍛鍊,最簡單的解決方法是使用一個switch聲明:

char op = ...  
int lhs = ... 
int rhs = ... 
int res = 0; 
switch(op) { 
    case '+': 
     res = lhs + rhs; 
    break; 
    case '-': 
     res = lhs - rhs; 
    break; 
    case '*': 
     res = lhs * rhs; 
    break; 
    case '/': 
     res = lhs/rhs; 
    break; 
    case '%': 
     res = lhs % rhs; 
    break; 
} 
+0

非常感謝您的幫助。我想確保在該語言中沒有可用的算術轉換。 –

+7

@DerekW:不,C++不包括(在標準中)任何類型的表達式評估器。 C++中的運算符由編譯器解析,並且在運行時沒有它們的概念。 –

+0

謝謝澄清。 –

10

由於@克里斯評論說,你可以製作一張人物函子:

std::map<char, std::function<double(double,double)> operators{ 
    { '+', std::plus<double>{} }, 
    { '-', std::minus<double>{} }, 
    { '*', std::multiplies<double>{} }, 
    { '/', std::divides<double>{} } 
}; 

double apply(double lhs, double rhs, char op) 
{ 
    return operators[op](lhs, rhs); 
} 

如果您使用不代表已知運算符的字符調用該函數,則會拋出std::bad_function_call

它也將在地圖上對這種未知字符創建不必要的項目,以避免你可以把它稍微complciated:

double apply(double lhs, double rhs, char op) 
{ 
    auto iter = operators.find(op); 
    if (iter == operators.end()) 
    throw std::bad_function_call(); 
    return (*iter)(lhs, rhs); 
} 

(NB它使用C++ 11層的功能,但可以很容易地被翻譯爲C++ 03,使用boost::functionstd::tr1::function