How to establish operator precedence? - c++

I am trying to create an infix to postfix math statement conversion function. I am using a stack to store operators, and if the current index has greater precedence, it is supposed to be pushed onto the stack. We are using operators like {,[,(,+,-,*,/,%. I am getting strange behavior whenever I try to compare these values (stringIndex < operator_stack.top()). I suspect this is because it is comparing the ASCII values. Is there a way to override these values with my own (for example, change * to have greater precedence than +)?

Are you doing some sort of ASCII comparison? That's probably a mistake. I would create an Operator class and program a precedence check. Then you would see a * and create a Multiply Operator, and that's what you push onto your stack.

Related

Using ++ as a prefix to a statement of access through class member not causing an error

I am kind of confused right now, I was running the following code:
std::vector<int> test{1, 5, 10};
++test.at(1); // I'm trying to increment that number 5 to six, which works
std::cout << test.at(1) << std::endl; // Prints out 6 to the console
I was expecting it to give me a compiler error because as I had read from about the operator precedence that the . (for member access) and the increment operator (++) have the same precedence, but they read left to right on a statement, from what I understood anyways. So in the code shown above I thought it would have been equal to saying (++test).at(1), which obviously causes a compiler error. Why isn't that the case even though the associativity is left to right, why is it reading it (from what I think) like this... ++(test.at(1))? If they have the same precedence wouldn't it, just like in maths, for example, use the ++ first and then the .?
True, postfix increment (a++) and member access (.) have the same precedence.
But you're using prefix increment (++a).
Consult cppreference's precedence chart.
Indeed, test++.at(i) would error for the reasons you give, though as readers of the code we would not be in any way surprised in that case.
Function calls have a higher operator precedence than unary operators like "++". The function call at() gets resolved first, and so the increment operator takes place on what it returns instead of the container.
https://en.cppreference.com/w/cpp/language/operator_precedence
EDIT: As Asteroids With Wings pointed out in their answer, only the prefix version of "++" has lower precedence than the function call. The postfix "++" is at the same level of precedence.

shunting Yard Algorithm, any changes?

I have implemented shunting yard algorithm in C++11 according to what is mentioned in wikipedia:
This implementation does not implement composite functions,functions with variable number of arguments, and unary operators.
while there are tokens to be read:
read a token.
if the token is a number, then:
push it to the output queue.
else if the token is a function then:
push it onto the operator stack
else if the token is an operator then:
while ((there is a operator at the top of the operator stack)
and ((the operator at the top of the operator stack has greater precedence)
or (the operator at the top of the operator stack has equal precedence and the token is left associative))
and (the operator at the top of the operator stack is not a left parenthesis)):
pop operators from the operator stack onto the output queue.
push it onto the operator stack.
else if the token is a left parenthesis (i.e. "("), then:
push it onto the operator stack.
else if the token is a right parenthesis (i.e. ")"), then:
while the operator at the top of the operator stack is not a left parenthesis:
pop the operator from the operator stack onto the output queue.
/* If the stack runs out without finding a left parenthesis, then there are mismatched parentheses. */
if there is a left parenthesis at the top of the operator stack, then:
pop the operator from the operator stack and discard it
/* After while loop, if operator stack not null, pop everything to output queue */
if there are no more tokens to read then:
while there are still operator tokens on the stack:
/* If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses. */
pop the operator from the operator stack onto the output queue.
exit.
As you can see it's mentioned that this algorithm doesn't deal with unary operator, suppose I have one ! which is stronger than all other operator, what changes should I make to my algorithm if any?
Some Legal Examples of using ! operator:
!1
! 1
! (1)
!( 1 + 2)
Plus one small question, does this algorithm deal with wrong syntax like 1==2 (I supposed that yes it does)?
Question 1:
In order to make your algorithm work you should parse the prefix operator ! before the infix operators, simply treating it as if it was an open parenthesis ( (then you need to tweak the stack virtual machine to allow this kind operator).
I suggest moving the if check for the parenthesis before the infix operator (it doesn't change much but it's more readable).
I will also say that if you want to achieve things like operator precedence, postfix operators and mixfix operators all together you should switch to a Pratt parser (which is much easier to work with).
Question 2:
The parser here doesn't deal with operations like 1 == 2, it only parses them. The stack based virtual machine deals with them and 1 == 2 is a completely fine comparison since it is supposed to return false. This if you plan to have boolean expressions as well as arithmetic expressions.
EDIT 1:
The "tweak" (which partially solves the issue): consider the operator as right associative and make its precedence higher than the other operators.
EDIT 2:
This (as pointed out in the comments by #dure) is just a tweak, since il will cause the parser to parse prefix and postfix operators without distinction and needs further care to avoid bugs.

Regex for finding the index of Mathematical Operators

I am writing a program that takes a string of a mathematical expression, converts it to postfix notation. Which I have done, I am now trying to figure out how to evaluate this expression. I have left it in the data type of a queue, so my idea is to try and find the index of the first operator, then find the two numbers the come before it, send those to a new function which will evaluate them based on which operator is found (so one function for adding, one for subtracting ... etc). Im having trouble figuring out how to grab the index though.
Im trying to use the Queue method of indexOf and then passing it a regex for those operators. using \\W
y is a Queue. i've never used this type of character code before.
var z = y.indexOf("[\\W]")
i would like it to return the index of the first operator, in the case i currently have it is a "+"
currently that doesent find anything. i've also tried dropping those brackets an example Queue is
Queue(-1, 2, 3, *, +, 10, +)
Queue(1, 2, +)
which does mean i need a way to differ if its just a - or if its tied to the number. These are all Strings inside of the Queue
You have to
y.indexWhere(_.matches("\\W"))

dot operator order of evaluation in c++

I am reading "C++ Primer (5th Edition)" and I've run in something I'm not sure I understand correctly.
The example is pretty much similar to one they gave in the book. Imagine we have some function that returns string (or any class that has non-static members):
string some_function(par1, par2) {
string str;
// some code
return str;
}
I know that you can use the return value of any function to access its members, i.e. something like this is valid:
auto size = some_function(arg1, arg2).size(); // or whatever member of class
However, since the dot operator . and function call operator () have left to right grouping and same precedence, the above expression should be something like this:
(some_function(arg1, arg2)).size()
I suppose I am right so far? The thing I don't understand here is order of evaluation. Since order of evaluation is not specified for . operator, it means that either some_function(arg1, arg2) or size() will be evaluated first. But how can it evaluate size() first if it doesn't know on which object is it working on? This implies that order of evaluation should be fixed from left to right, but it is not. How is this possible?
Another example is something like this:
cin.get().get();
Again, it seems like first cin.get() should be evaluated before second get() since it won't know on which object is it working, but this doesn't seem to be necessarily the case.
Operators of the same precedence are evaluated according to their associativity, which you correctly observe is left-to-right for the operator group containing the function call and element selection operators. Therefore, yes, given the expression
x = foo().bar();
The order of operations is
x = (((foo()).bar)());
accounting for relative precedence and associativity of all operators involved. No one writes code in that manner, though.
Likewise, given
cin.get().get()
the order of operations is
(((cin.get)()).get)()
, so yes, the precedence rules result in the cin.get() sub-expression being evaluated first, yielding the object to which the second . (and thence the rest of the expression) is applied.

How do I set a precedence value to operators such as '*', '/', '+', and '-.

I either want to set them to bool values or simply integer values so that I can tell my function to multiply/divide these two integers before I add/subtract them to another operand.
Here is my code:
while (!S.empty() && **PRECEDENCE**next <= **PRECEDENCE**S.top())
{
temp = S.top();
S.pop();
postfix.append(temp);
}
Where S is for the stack. So let's say next is the * token and S.top() is '+', so * takes priority over +, so I need to assign a value to * and + so that when they are compared to one another, their values are compared. So the value of * is 1 whereas the value of + is 0.
OMG, there are many methods to do this.
Look up table
You could create a table of records and search the table for the operator, then retrieve the precedence value.
Use switch statement
I don't advise, but it is similar functionality of mapping a precedence to an operator.
Use std::map
Same concept as the other two, except using std::map<char, int> for operator character and precedence.
Hard code the precedence
The operators you compare for first will have the highest precedence. The next operators checked will have lower precedence.
Search the Web and StackOverflow
Hint: Other people have done this assignment. Search StackOverflow or the web for:
"c++ postfix operator precedence"
"c++ calculator operator precedence"
"c++ calculator operator evaluation"
"c++ postfix operator evaluation"
Or use other synonyms that I haven't listed.
Research before posting
Be as smart person and cheat by researching and seeing what other people have done. Before posting questions here.
Use a debugger
Use a debugger or print statements to see where your issues lie.
If you are still stumped, post the issue, your minimal code and the expected behavior.