Error: deque iterator not dereferenceable

前端 未结 3 1448
予麋鹿
予麋鹿 2021-01-20 05:07

I\'m trying to create a program that converts an arithmetic expression from infix to postfix form. As long as I don\'t call the \"infixToPostFix\" function, the program runs

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 05:49

    I ran into this problem too. I think the problem is in this sort of code:

        else if (token.getType() == CLOSE)
        {
            token = stack.top();
            stack.pop();
    
            while (token.getType() != OPEN)
            {
                postfix.push_back(token);
    
                token = stack.top();
                stack.pop();
    
            }
        }
    

    The problem is that 'token' is a reference to the top, not a copy. So you can't pop the stack until you are done working with token. In my case, it often still worked because the information was still present, but then it would crash at weird times. You need to organize this code in a different way to pop only after you done working with 'token'.

    Maybe something like:

    else if (token.getType() == CLOSE)
    {
        token = stack.top();
        Token saveToken = new Token(token);  // Or something like this...
        stack.pop();
    
        while (saveToken.getType() != OPEN)
        {
            postfix.push_back(saveToken);
    
            token = stack.top();
            delete saveToken;     // ugh
            Token saveToken = new Token(token);
            stack.pop();
    
        }
        delete saveToken;  //ugh
    }
    

提交回复
热议问题