0
Я успешно реализовал алгоритм маневрового двора в C++ для преобразования выражения infix в постфиксное выражение (RPN). Мне нужно изменить свой алгоритм, чтобы вернуть выражение префикса (polish), и я не знаю, как это сделать.алгоритм маневрового домика в префиксную реализацию
void Prefix::fromInfix()
{
//The stack contain the operators
std::stack<std::string> pile;
//This is the output
std::vector<std::string> sortie;
//The input is the std::vector<std::string> _expression
pile.push("(");
_expression.push_back(")");
for (auto iter = _expression.begin(); iter != _expression.end(); iter++)
{
//statOperator detect if the token is an operator and the priority of the operator.
short op = statOperator(*iter);
if (*iter == "(")
pile.push(*iter);
else if (*iter == ")")
{
while (pile.top() != "(")
{
sortie.push_back(pile.top());
pile.pop();
}
pile.pop();
}
else if (op)
{
while (!pile.empty())
{
short op2 = statOperator(pile.top());
//if op2 is is have the priority and isn't a parenthesis.
if (op <= op2 && op2 != 3)
{
sortie.push_back(pile.top());
pile.pop();
}
else
break;
}
pile.push(*iter);
}
else
sortie.push_back(*iter);
}
_expression = sortie;
}
Таким образом, вместо вывода AB + вы выводите + AB? Если вы понимаете, как работает маневровый двор для вывода постфикса, вы должны уметь немного подумать и вывести префикс. Учтите, что postfix - это просто обход после дерева выражений. Префикс - это * pre * порядок прохождения. –
BTW, C++ 11 имеет диапазон для циклов: 'for (токен строки: _expression)' –