I'm trying to write a function, that goes within my main program, that will compare the precedence of operators being input by the user. The function would look for the following operators:
+, -, * , / with *, / having the highest precedence and +, - having the lowest precedence.
The operators with the lowest precedence go on the bottom of a stack while those with the highest precedence go on the top of the stack. So if a user types in +-*/, */+- should be displayed in the terminal.
Any ideas on how I should go about this?
Just sort them using std::sort with a custom predicate.
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);
}
Obviously, you can add other operators simply by adding them into the precedence function.
Read all of the operators into a std::string. Write a function with the following type:
bool is_higher_precedence(char lhs, char rhs);
This function should return whether lhs has higher precedence than rhs.
You can then use this function as the functor parameter of std::sort to sort the operators by precedence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With