Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Precedence Function

Tags:

c++

stack

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?

like image 205
UndefinedReference Avatar asked Dec 06 '25 08:12

UndefinedReference


2 Answers

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.

like image 180
Peter Alexander Avatar answered Dec 07 '25 22:12

Peter Alexander


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.

like image 43
James McNellis Avatar answered Dec 07 '25 20:12

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!