C++ – How to Store Math Expressions in a List

cdata structuresparsing

I am parsing a infix math expression to a postfix form. I want to store it in a list like [4.5, 3, 0.25, +, -] so that I can process it once it's parsed. I could store it in a string again, but I would have to parse it twice. The problem is that I don't know how to store operators and operands in the same list. I thought of two children classes of a common parent, but they are totally different.

What is the best way to achieve this?

Best Answer

The problem is that I don't know how to store operators and operands in the same list

Consider the composite design pattern:

enter image description here

The article goes on to show a math expression example:

enter image description here

This lets you build your own tree. If you like you can also store all elements in a list but doThis() is using the tree to traverse.

What might be a bit confusing is that it shows all the operations as methods. Instead you could store the operation in the composite node. Rename doThis() to calculate() and now you can call root.calculate() to compute the whole expression. You'd be able to do this on any node. I'd have the interface look like this:

<<interface>>
Component
---------  
+calculate()  
+getPrefixString()  
+getInfixString()  
+getPostfixString()  
+addElement(Component component)  

None of this get's you out of having to reparse elements as you visit each one. Here's a way to avoid that:

enter image description here

Now you can do all parsing up front before you construct the tree. doThis(), or calculate() as I'd rename it, knows which operator to use polymorphically.

Since these all have the same type, Component, you are free to store them in a list, array, or whatever. But the way they link together is still a tree.

You've expressed a construction concern regarding infix notation. Consider the builder pattern. It's good at constructing composites. The link I provided takes you through refactoring just such a case. I think you'll find enough power that you could deal with infix, prefix, and postfix.

Related Topic