• Advertisement
Sign in to follow this  

Knowing Operator Precedence

This topic is 1922 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok so I had a quick question on how some of y'all would attack this.

This is a school assignment so I won't be giving code nor do I really want any code. Just trying to get some ideas on some of the best ways to implement this small thing.

The school assignment really just focuses on us building our own stack, which I got done really fast and I like how it is designed (for a simple Linked List based Stack). We are using this stack for infix to postfix conversion which I also understand and can code. The only thing that is giving my brain fits right now is a good way to implement operator precedence. I need to check whether or not the operator I just read in the input is of higher precedence than the operator that is on top of the stack. What would be some ways to do some quick checking for this?

Even though I am not expecting code, C++ is the language. Though just some ideas on how to put this in code would be great.

If you have any question then just ask.

Thanks,
Chad

EDIT: to make things simpler right now we can ignore parenthesis Edited by Chad Smith

Share this post


Link to post
Share on other sites
Advertisement
This sounds like the classic RPN calculator assignment.

[url="http://stackoverflow.com/a/1933976/101767"]This answer[/url] shows you a C++ stack based implementation.

Share this post


Link to post
Share on other sites
Thanks, though that is not entirely it. The assignment really is just converting a very simple infix expression to a postfix expression

Example
[code]
infix: 3+2
postfix: 32+

or

infix: 8-3+2-1
postfix: 83-2+1-
[/code]

When the operator (or just character as it is just a string) I am reading is of equal or lower precedence then I just pop the top element until it isn't, and then push it onto the stack.

As of right now I just decided to go ahead and do some if else if statements over each operator to see. They are pretty long though for a simple assignment that isn't focusing on operator parsing really then I believe it will be fine.

Though any other suggestions are nice. I will also take a look at the code in the link though to see if I can by chance learn something.

Chad

Share this post


Link to post
Share on other sites
You could have a map where you map each operator to a priority-value.
Then just compare priority values in a single if

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement