2016-04-15 62 views
0

我正在研究我的数据工作簿中的项目,并且由于某些原因,即使它几乎逐字写入了我仍然遇到的无法识别的运行时错误。noob构造函数中的迭代器运行时错误

这里是我的代码:

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))

在主曰:

调试断言失败! ...表达:字符串迭代器不兼容

我读过有关的错误的一切说,当你比较迭代器它发生,但是这没有任何意义,如果我甚至无法通过构造函数得到它。任何帮助更好地理解这将是美好的。提前致谢。

回答

2

string::const_iterator iter;不是初始化的迭代器。

然后您正在读取它的值iter != expression.end()

这样做的行为是undefined

您的意思是string::const_iterator iter = expression.begin();

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 
+0

哦,我的上帝。非常感谢你。我真是个白痴。我在工作时用这个词写了这个词,今天早上把它粘贴到了满是错误的白垩上。我甚至没有意识到我错误地移动了它。非常感谢。 – Sami