0

Friends, I am having a really hard time figuring out why this code is breaking when it is. I am trying to write a function that returns true if an equation is balanced (meaning that it has a close parenthesis for every open one). Equations are input to the function as strings. I know that code like this exists all over the internet, but I am trying to produce original content for a school assignment. The main function (shown below) inputs a example of when the function breaks, it doesn't break every time.

#include <vector>
#include <string>
#include <iostream>
#include <map>

using namespace std;

bool isBalanced(string expression)
{
map<char,char> inv;
inv['(']=')';
inv['[']=']';
inv['{']='}';
vector<char> brackets;
for(int i = 0; i < expression.length(); i++)
{
char c = expression.at(i); 
    if(c=='{'|| c=='}'||c=='('||c==')'||c=='['|| c==']')
    {
        brackets.push_back(c);
    }
}
for(int i=0;i<brackets.size();i++)
{
    cout << brackets[i];
}
cout  << endl;
for(int i=0;i<=brackets.size();i++)
{
    if(brackets[i]=='{'||brackets[i]=='('||brackets[i]=='[')
    {
        for(int j=i;j<=brackets.size();j++)
        {   
            cout << inv[brackets[i]];
            if(brackets[j]==inv[brackets[i]])
            {
                brackets.erase(brackets.begin()+j);
                break;
            }
            else if(j==brackets.size())
            {
                return false;
            }
        }
    }
if (i==brackets.size()) 
{
    return true;
}

}
}

int main()
{
    string expression ="(()";
    if(isBalanced(expression))
    {
        cout << "IT WORKED";
    }
    else
    {
        cout << "NOOOOOO!!";
    }

    return 0;
}

// what if there is an extra last bracket?
Sean Clancy
  • 661
  • 6
  • 14
  • Start by stepping through in a debugger. – Eric J. Oct 12 '15 at 00:29
  • Possible duplicate of [Definitive List of Common Reasons for Segmentation Faults](http://stackoverflow.com/questions/33047452/definitive-list-of-common-reasons-for-segmentation-faults) – CodeMouse92 Oct 12 '15 at 15:28

1 Answers1

0

You're using the wrong comparison operator in the loop. You should be using i < brackets.size() and j < brackets.size() instead.

gigaplex
  • 471
  • 2
  • 8
  • Thanks a bunch! I had added the = to the <= in those statements because the logic stops working with out them, so changing it back to just < made the seg fault go away, but the function is now returning true when it isn't supposed to and I can't figure that out ether. Thank you again for your help though. – Sean Clancy Oct 12 '15 at 00:55
  • I haven't had a close look at how the algorithm works, but my first guess is that your termination case needs to compare `i == brackets.size() - 1` before returning true. If `i == brackets.size()` then it has walked past the end of the container. – gigaplex Oct 12 '15 at 01:30