将所有运算符读入std::string。编写以下类型的函数:
bool is_higher_precedence(char lhs, char rhs);
Run Code Online (Sandbox Code Playgroud)
此函数应返回是否lhs具有比更高的优先级rhs。
然后,您可以将此函数用作函数的functor参数,std::sort以按优先级对运算符进行排序。
只需使用std::sort自定义谓词对它们进行排序。
int precedence(char op)
{
if (op == '*' || op == '/') return 0;
return 1;
}
bool comparePrecedence(char a, char b)
{
return precedence(a) < precedence(b);
}
int main()
{
char input[] = "+-/";
std::sort(input, input + 3, &comparePrecedence);
}
Run Code Online (Sandbox Code Playgroud)
显然,您可以通过将其他运算符添加到precedence函数中来添加其他运算符。