vector<char> conversion(string x) {
vector<char> data(x.begin(), x.end());
return data;
}
vector<Input*> conversion2(vector<char> rpn){
vector<Input*> input;
for(int i=0; i<rpn.size(); i++){
if(isdigit(rpn[i])){
input.push_back(new Integer(rpn[i]-'0'));
}
else if(rpn[i]=='+'||rpn[i]=='-'||rpn[i]=='/'||rpn[i]=='*'||rpn[i]=='^'){
input.push_back(new Operator(rpn[i]));
}
}
return input;
}
vector<char> shuntYard(string x) {
vector<char> expr = conversion(x);
vector<char> queue; stack<char> opStack;
map<char, int> opPrec;
opPrec['('] = -1;
opPrec['+'] = 1; opPrec['-'] = 1;
opPrec['*'] = 2; opPrec['/'] = 2;
opPrec['^'] = 3; opPrec['sqrt'] = 3;
bool lastWasOp = true;
for(int i=0;i<expr.size();i++){
if(isspace(expr[i])){
i++;
}
if (isdigit(expr[i])) {
// If the char is a number, add it to the output queue.
queue.push_back(expr[i]);
lastWasOp = false;
}
else{
switch (expr[i]) {
case '(':
opStack.push('(');
break;
case ')':
while (opStack.top()!=('(')) {
queue.push_back(opStack.top());
opStack.pop();
}
opStack.pop();
break;
default: //op precedence
{
if (lastWasOp) {
// Convert unary operators to binary in the RPN.
if (expr[i]=='-' || expr[i]=='+') {
queue.push_back('0');
} else {
throw domain_error(
"Unrecognized unary operator.");
}
}
while (!opStack.empty() &&
(opPrec[expr[i]] <= opPrec[opStack.top()])) //comparing stack operators
{
queue.push_back(opStack.top());
opStack.pop();
}
opStack.push(expr[i]);
lastWasOp = true;
}
}
}
}
while(!opStack.empty()){ //empty the final stack
queue.push_back(opStack.top());
opStack.pop();
}
return queue;
}
以上代码是计算器程序的一部分。程序从字符串(即&#34; 1 + 3-5 * 8)中获取用户的输入,然后转换为反向抛光表示法。&#39;从那里开始的目标是放入一个矢量,便于从反向抛光表示法形式计算。一切都按预期工作,但遗憾的是,程序无法识别用户输入的两位数字。如同,当&#34; 1 + 11&#34;由用户输入,正确地进入反向抛光表示法,但是&#34; 1 + 11&#34;在反向抛光表示法中表示为111+。这不允许正确的计算。我的问题是,我们如何(使用与我们当前代码类似的东西)使得双位数(或任何多位数)数字在矢量中单独表示?所以&#34; 1 + 11&#34;可以在向量中表示为{1,11,+}吗?
答案 0 :(得分:0)
使用正确的基本类型。例如,您可以使用std::string
,因此每个元素对应一个已解析的标记(数字或运算符)
我们希望您的实现具有小字符串优化。