我正在研究我的数据结构书中的一个项目,出于某种原因,即使它几乎逐字逐句,我仍然会收到我无法识别的运行时错误。
这是我的代码:
int main()
{
cout << "Enter an expression, to check if its balanced.\n";
string exp;
while (getline(cin, exp) && (exp != ""))
{
cout << exp;
if(is_balanced(exp))
{
cout << " is balanced.";
}
else
{
cout << " is not balanced.";
}
cout << "Enter another expression: \n";
}
return 0;
}
bool is_balanced(const string& expression) // pass reference to the input expression
{
//create stack to hold parantheses
stack<char> s;
bool balanced = true; //to hold return value
string::const_iterator iter;
expression.begin(); // sets a read-only iterator at the beginning of the expression
while (balanced && (iter != expression.end())) //while 'balanced' and not at end of expression cont. looping
{
char nx_ch = *iter;
if (is_open(nx_ch))
{
s.push(nx_ch);
}
else if (is_closed(nx_ch))
{
if (s.empty())
{
balanced = false;
}
else
{
char tp_ch = s.top(); // if the stack isn't closed set the char as tp for comparisson
s.pop(); // remove top char
balanced = OPEN.find(tp_ch) == CLOSE.find(nx_ch);
}
}
++iter;
}
if(!s.empty())
{
balanced = false;
return balanced && s.empty();
}
else
{
return balanced && s.empty();
}
}
此行发生错误:if(is_balanced(exp))
在主要内容中读取:
调试断言失败! ...表达式:字符串迭代器不兼容
我读到的关于错误的所有内容都说当你与迭代器进行比较时会发生这种情况,但如果我甚至无法通过构造函数获取它,那就没有意义了。任何帮助更好地理解这一点都会很精彩。提前致谢。
答案 0 :(得分:2)
string::const_iterator iter;
初始化迭代器。
然后您正在iter != expression.end()
中阅读其值。
这样做的行为是 undefined 。
您的意思是string::const_iterator iter = expression.begin();
吗?
答案 1 :(得分:1)
这不是你如何设置变量:
string::const_iterator iter;
expression.begin(); // sets a read-only iterator at the beginning of the expression
这是您设置变量的方式:
string::const_iterator iter = expression.begin(); // sets a read-only iterator at the beginning of the expression