I have to write a function that accepts a string and returns a bool. The string passed in is a series or different parenthesis opened or closed ex.({[]}) and returns whether the 'parens' are well-balanced. This has to be implemented by adding items to a stack. I am getting the following error:
parenMatching_demo.cpp:18:12: error: no match for 'operator==' in 'c == '('
The psudocode is:
matcher(expression)
for each character in expression
if the character is an opener
push on stack
else if the character is a closr
if stack is empty return false
if the (opener at) the top of the stack does not match the closer
return false
pop the stack
if the stack is not empty return false
return true
This is what I have.
template <typename T>
bool parenMatching(string c) {
stack<string> s;
for (int i = 0; i < s.size(); i++) {
if (c == '(' || c == '[' || c == '{' || c == '<')
s.push(c);
else if (c == ')' || c == ']' || c == '}' || c == '>') {
if (s.empty()) return false;
if (s.top() != '(' || s.top() != '[' || s.top() != '{' || s.top() != '<')
return false;
s.pop();
}
}
}
One problem is the type of the stack, it should be
stack<char> s;
Then the for loop, the condition should be
i < c.size()
The next problem is
if (c == '(' || c == '[' || c == '{' || c == '<')
does not compare the character of the string c at i, so you need
const char c2 = c[i];
if (c2 == '(' || c2 == '[' || c2 == '{' || c2 == '<')
If you need help to fix the rest, let me/us know :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With