1

こんにちは)これは、中置式から後置式に変換するための私のコードですが、取得した後置式をどのように評価できるか理解できません。ヒントがあれば非常に感謝します。コードを要求しているわけではありませんが、それは役に立ちます。

#include <iostream> 
#include <stack> 
#include <string>

using namespace std; 
bool operation(char b) 
{
    return b=='+' || b=='-' || b=='*' || b=='/' ; 

} 

bool priority(char a, char b) 
{
    if(a=='(')
    {
        return true; 
    } 
    if(a=='+' || a=='-') 
    {
        return true; 

    } 
    if(b=='+' || b=='-') 
    {
        return false; 
    } 

    return true; 

} 
int main() 
{

    string a;
    string res; 
    stack<char> s; 
        cin>>a; 
    for(int i=0; i<a.size(); i++) 
    {
        if(a[i]!='(' && a[i]!=')' && operation(a[i])==false) 
        {

            res=res+a[i]; 
        } 
        if(a[i]=='(') 
        {
            s.push(a[i]) ; 
        } 
        if(a[i]==')') 
        {
            while(s.top()!='(') 
            {
                res+=s.top(); 
                s.pop();
            }
            s.pop(); 
        } 
        if(operation(a[i])==true) 
        {
            if(s.empty() || (s.empty()==false && priority(s.top(), a[i])) ) 
            {
                s.push(a[i]); 
            }
            else 
            {
                while(s.empty()==false && priority(s.top(),a[i])==false ) 
                { 
                    res+=s.top(); 
                    s.pop(); 
                }
                s.push(a[i]) ; 
            }

        } 

    } 
    while(s.empty()==false) 
    {
        res+=s.top(); 
        s.pop(); 
    } 
    cout<<res; 




    return 0; 
} 

PS コメントはありませんが、コード自体は一目瞭然だと思います))
PPS よろしくお願いします。

4

1 に答える 1

0

スペースで区切られた接尾辞式を作成する場合、評価のアルゴリズムに従うだけで、以下が評価器をコーディングする最も簡単な方法の 1 つになります。

これは、RPNのようなものを想定し5 1 2 + 4 * + 3 -ています(スペースで区切られています)

int evaluate_posfix ( const std::string& expression )
{

    int l,r,ans;
    std::stringstream postfix(expression);
    std::vector<int> temp;
    std::string s;
    while ( postfix >> s )
    {
        if( operation(s[0]) )
        {
            //Pull out top two elements
            r = temp.back();
            temp.pop_back();
            l = temp.back();
            temp.pop_back();
            // Perform the maths
            switch( s[0])
            {
                case '+': ans =  l + r ; break;
                case '-': ans =  l - r ; break;
                case '*': ans =  l * r ; break;
                case '/': ans =  l / r ; break; // check if r !=0
            }

            temp.push_back( ans ); // push the result of above operation
        }
        else
        {
            temp.push_back( std::stoi(s) );
        }
    }

    return temp[0] ; //last element is the answer
} 
于 2014-03-02T14:39:36.607 に答える