[英]Modifying the Shunting Yard Algorithm (c++)
我有一個工作正常的調車場算法,但我注意到一個特殊的怪癖:
1 + ( 3 * ( 4 + 5 ) )
正確解析為
1 3 4 5 + * +,
但
1 + (3 * (4 + 5))失敗,並解析為
1 * + 5))+
我想讓它正確地解析第二個問題,以便結果與第一個相同。 我該怎么做?
注意:我從Wikipedia派生了算法: http : //en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail
我的算法代碼是:
string switchingYard(string input)
編輯:好的,所以我有了一個主意。 , passing in the substring of the input string which starts at the '3' character? I would then only need to add the shunted string to the output vector, and call ignore on the stringstream! I'm talking about making these changes: 因此,當解析器遇到'(3'令牌時,它將以其他方式將兩個字符視為一個,並丟棄整個內容,但是如果我調用該函數,傳入以'開始的輸入字符串的子字符串,該怎么辦? 3'字符?然后我只需要將已分流的字符串添加到輸出向量,並在字符串流上調用ignore!我正在談論進行以下更改:
string switchingYard(string input, int depth)
變
string switchingYard(string input, int depth)
和
if((token[0] == '(' || token[0] == ')') && (isdigit(token[1]) || token[1] == '.' || isOperator(token[1])) { string shunted_recur = out.push_back(switchingYard(input.substr(io.tellg()+1),depth+1)); }
被添加到while循環的末尾。
有什么想法嗎?
您的問題是解析器使用以下命令讀取字符串:
io >> token;
我認為,簡單的解決方案是一次只讀取一個字符。 例如
char ch;
io >> ch;
我實際上會編寫一個讀取令牌的函數-它會知道諸如“數字序列就是數字”之類的東西,並分離出運算符,括號等。它將返回持有“類型”的對象(類或結構類型)元素”和“值”(如果有)-因此可以是“數字”和“ 4711”值,也可以是“運算符”,“ +”值。
您需要為令牌生成器提供一個“狀態”,其中應包含一個“超前”字符(一個字符就足夠了),以便您可以在超過數字末尾時停止,然后選擇一個下次“不再是數字”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.