平衡的表达与堆栈
balanced expression with stacks
请告诉我我做错了什么?我需要确保表情平衡我试了所有方法,但都没有错误
int main() {
ifstream infile;
infile.open("input.txt");
string exp;
cout << "Enter an expression ";
while (getline(infile, exp)) {
cout << exp << ": ";
if (matcher(exp))
cout << "Matched ok" << endl;
else
cout << "Match error" << endl;
cout << "Enter an expression: ";
}
cout << "--- Done ---" << endl;
return 0;
}
int matcher(string expression) {
stack<char> s;
for (int i = 0; i < expression.length(); i++) {
if (isOpener(expression[i]))
s.push(expression[i]);
else if (isCloser(expression[i])) {
if (s.empty()) return 1;
char opener = s.top();
s.pop();
if (!matches(opener, expression[i])) return 1;
}
}
if (!s.empty()) return 1;
return 0;
}
一个明显的问题-您的matcher
函数似乎返回1
失败(不匹配)和0
成功,但您的main
打印ok
如果matcher
返回非零…
我将假定isOpener()
和matches()
正常工作,因为您没有显示它们。
如果是这样,问题是你误解了int -> bool
转换。零转换为false
,非零整数转换为true
。您最好声明matcher()
返回bool
,并直接从中返回true
或false
。您将希望在现在返回1
的地方返回false
,在现在返回0
的地方返回true
。
相关文章:
- 算法问题:查找从堆栈中弹出的所有序列
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么调用堆栈数组会导致内存泄漏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的 int main() 中出现堆栈溢出错误
- 堆栈和队列是否像C++中的数组一样传递?
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 从堆栈分配的原始指针构造智能指针
- 堆栈问题(平衡表达式问题集)
- 使用堆栈从黑客等级中解决平衡括号检查的错误
- 使用 .Net 4.0 时出现堆栈不平衡错误,但在使用 .Net 2.0 时不调用堆栈不平衡错误
- 平衡括号 - 堆栈未被认为是空的
- 堆栈:C 失败中的平衡括号
- 以下代码使用堆栈标识平衡括号有什么问题
- 使用堆栈来确定表达式是否具有平衡圆括号
- 由于指针导致堆栈不平衡
- 平衡的表达与堆栈