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?
 
    