取消排队迭代器不可取消引用
Dequeue iterator not dereferencable
通过在网上做一些研究,我发现这是由于试图从空堆栈中弹出某些内容而导致的错误。在我的代码中,我认为我试图通过将堆栈的顶部存储在名为 c
的临时字符串中来确保不会发生这种确切的事情,但由于某种原因,错误不断发生。这是一个与将中缀表示法转换为后缀表示法相关的项目。当我输入1+2+3
时,我应该得到12+3+
,但相反,发生了此错误。错误发生在循环的优先级中。
stack <string> InfixToPostfix(char * expr)
{
// YOUR CODE STARTS HERE!
char* token;
stack<string> s;
string postfix;
stack<string> p;
// use stack s to manipulate the infix to postfix
s.push("(");
token = strtok (expr," "); // get the first token
while(!s.empty())
{
if(token=="(")
{
s.push(token);
}
else if(token==")")
{
string c=s.top();
s.pop();
while(c != "(")
{
postfix += c + " ";
c = s.top();
s.pop();
}
}
else if(isNumber(token))
{
postfix+=token;
}
else
{
while(precedence(s.top())>=precedence(token))
{
//put on bottom if need be
string c = s.top();
s.pop();
postfix += c;
postfix += " ";
}
s.push(token);
}
token = strtok(NULL, " "); // use blanks as delimiter
if (token == NULL) // no more tokens, exit the loop
break;
}
p.push(postfix);
return p;
}
在 main while 循环中的 if 语句中,您有一些调用来pop()
,而无需检查 deque 是否为空,例如
while(c != "(") {
postfix += c + " ";
c = s.top();
s.pop();
}
这可能应该是:
while(c != "(" && !s.empty()) {
}
下面同
while(precedence(s.top())>=precedence(token))
{
//put on bottom if need be
string c = s.top();
s.pop();
postfix += c;
postfix += " ";
}
s.push(token);
这些很可能是无效访问的来源。通常,您应该尝试使用gdb
或valgrind --tool=memcheck
,它们将显示错误源。或任何其他调试器真的...
此外,如果令牌是我怀疑的单个字符,请使其成为char
而不是char *
。然后在您的令牌比较中使用 token == ')'
(注意单引号(来比较两个字符,而不是您现在拥有的将字符指针与字符串文字进行比较......这可能也适用于您维护的所有数据结构,这些数据结构应该成为,例如 deque<char> ...
最后拿起任何一本像样的入门C++书并阅读它。你以后会感谢自己的。
相关文章:
- C++取消引用指针.为什么会发生变化
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 取消引用运算符不能重载
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++ 关于指针取消引用的技术问题
- 没有取消引用/解包对象的标准方法?
- 列表 iter 不取消引用 使用列表进行插入排序
- 在这个函数中是有缺陷的,因为取消引用 null 是无效的,所以我想更改代码
- 取消引用结束指针到数组类型的一个
- 取消引用向量时出现问题
- 取消引用指向整数的指针时获得不同的结果
- C++:取消引用十六进制值,有点语法问题
- C/C++ 取消引用错误:在空检查之前取消引用
- 取消引用后C++空测试
- 对于实际指针类型,用于检测类似指针(可取消引用)类型的模板函数失败
- 升压::可选<bool>取消引用
- 如何确定类型在 C++03 中是否可取消引用
- 数组迭代器不是可取消引用的错误
- 迭代器不是可取消引用的堆栈(表达式树)和循环无法正常工作
- 列出迭代器而不是可取消引用的运行时