取消排队迭代器不可取消引用

Dequeue iterator not dereferencable

本文关键字:可取消 引用 不可取 迭代器 排队 取消      更新时间:2023-10-16

通过在网上做一些研究,我发现这是由于试图从空堆栈中弹出某些内容而导致的错误。在我的代码中,我认为我试图通过将堆栈的顶部存储在名为 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);

这些很可能是无效访问的来源。通常,您应该尝试使用gdbvalgrind --tool=memcheck,它们将显示错误源。或任何其他调试器真的...

此外,如果令牌是我怀疑的单个字符,请使其成为char而不是char *。然后在您的令牌比较中使用 token == ')'(注意单引号(来比较两个字符,而不是您现在拥有的将字符指针与字符串文字进行比较......这可能也适用于您维护的所有数据结构,这些数据结构应该成为,例如 deque<char> ...

最后拿起任何一本像样的入门C++书并阅读它。你以后会感谢自己的。