具有前缀的段错误

时间:2015-12-09 00:08:58

标签: c++ unix prefix fault infix-notation

尝试将中缀表达式转换为前缀顺序时,我遇到了分段错误。我有一个后缀使用相同的逻辑工作正常问题似乎是我尝试反向读取中缀表达式,但我不完全确定为什么它是错误的。任何帮助将非常感谢以下是相关代码:

int ParseTree::prefix(string infix)
{
        vector<string> exp;
        stringstream ss(infix);
        string tok;

        while(getline(ss,tok,' '))
        {
                exp.push_back(tok);
        }
        vector<string> prefix;
        stack<string> s;

        for(unsigned int i = exp.size() - 1; i >= 0 ; i--)
        {
                if(parseTry(exp[i]))
                {
                        prefix.push_back(exp[i]);
                }
                if(exp[i] == "(")
                {
                        s.push(exp[i]);
                }
                if(exp[i] == ")")
                {
                        while(!s.empty() && s.top() != "(")
                        {
                                prefix.push_back(s.top());
                                s.pop();
                        }
                        s.pop();
                }
                if(isOperator(exp[i]) == true)
                {
                        while(!s.empty() && priority(s.top()) >= priority(exp[i]))
                        {
                                prefix.push_back(s.top());
                                s.pop();
                        }
                        s.push(exp[i]);
                }
        }
        while(!s.empty())
        {
                prefix.push_back(s.top());
                s.pop();
        }

        for(unsigned int i = 0; i < prefix.size(); i++)
        {
                cout << prefix[i] << " ";
        }
        return 0;
}
int ParseTree::priority(const string &s)
{
        if(s == "*" || s == "/")
        {
                return 2;
        }
        if(s == "+" || s == "-")
        {
                return 1;
        }
        else
        {
                return 0;
        }
}

bool ParseTree::parseTry(const string &s)
{
        bool number = false;
        for(unsigned int i = 0; i < s.size(); i++)
        {
                if(!isdigit(s[i]))
                {
                        number = false;
                }
                else
                {
                        number = true;
                }
        }
        return number;
}

bool ParseTree::isOperator(const string &s)
{
        return (s == "+" || s == "-" || s == "*" || s == "/");
}

0 个答案:

没有答案