Greetings to all.
I am writing unit tests for testing the Reverse Polish Notation. The first thing i want to test is to make sure that the expression entered is valid. Apart from testing that there is an operator (/+*-), i want to test for brackets. I want to have something like this
This code will fail for expressions with nested brackets: 5 * (4 - (5 + 2) * 4)
Also it'll return false positives if there's at least one correct bracket set before an incorrect one, e.g. infix2 will be a false positive.
Since you're going to iterate through the whole string anyway so why not do this?
1 2 3 4 5 6 7 8 9 10 11
bool hasCorrectBrackets(const std::string &infix)
{
int bracketSum = 0;
for (unsignedint idx = 0; idx < infix.length(); idx++) {
if (infix[idx] == openBrace)
++bracketSum;
if (infix[idx] == closeBrace)
--bracketSum;
}
return (bracketSum == 0);
}