Error: deque iterator not dereferenceable

前端 未结 3 1426
予麋鹿
予麋鹿 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
    }
    
    0 讨论(0)
  • 2021-01-20 05:52

    You are calling top on empty stack, just follow the code for your test.

    1. you start with an empty stack
    2. you encounter a VALUE, you don't change stack
    3. you encounter an OPERATOR and attempt to access stack.top()
    0 讨论(0)
  • 2021-01-20 06:10

    stack is implemented using container, since stack is container adaptor, by default deque is used. In probably one line of your code - you call pop/top on empty stack, that is not allowed.

    trace show, that error is after Token +. Problem is here:

       else if (token.getType() == OPERATOR)
        {
            Token topToken = stack.top();
    

    You try to top from empty stack, since stack in case, where is only NUMBER token before OPERATOR token, is empty.

    0 讨论(0)
提交回复
热议问题