访问堆栈和队列时发生运行时错误

Runtime error accessing stacks and queues

本文关键字:运行时错误 队列 堆栈 访问      更新时间:2023-10-16

我正在做UVa在线评委问题-11995。调试后,我发现一些东西让我感到困惑。

这是我调试代码之前的部分,我得到了一个"运行时错误"。

int take;
scanf("%d", &take);
int out_s;
int out_q;
int out_p;
if(sta){
     out_s = s.top();
     if(!s.empty() && out_s == take) s.pop();
     else sta = 0;
}
if(que){
     out_q = q.front();
     if(!q.empty() && out_q == take) q.pop();
     else que = 0;
}
if(pri){
     out_p = p.top();
     if(!p.empty() && out_p == take) p.pop();
     else pri = 0;
}

在我简单地删除了一些愚蠢的整数赋值后,我得到了一个"已接受"的

int take;
scanf("%d", &take);
if(sta){
     if(!s.empty() && s.top() == take) s.pop();
     else sta = 0;
}
if(que){
     if(!q.empty() && q.front() == take) q.pop();
     else que = 0;
}
if(pri){
     if(!p.empty() && p.top() == take) p.pop();
     else pri = 0;
}

我真的不明白为什么我会因为变量的分配而出现运行时错误。

这是我的全部代码:

using namespace std;
int main ()
{
    int n;
    while(scanf("%d", &n) != EOF){
        int comm;
        stack<int> s;
        queue<int> q;
        priority_queue<int> p;
        bool sta = 1;
        bool que = 1;
        bool pri = 1;
        for(int i = 0; i < n; i++){
            scanf("%d", &comm);
            if(comm == 1){
                int input;
                scanf("%d", &input);
                s.push(input);
                q.push(input);
                p.push(input);
            }
            else{
                int take;
                scanf("%d", &take);
                int out_s;
                int out_q;
                int out_p;
                if(sta){
                   out_s = s.top();
                   if(!s.empty() && out_s == take) s.pop();
                   else sta = 0;
                }
                if(que){
                    out_q = q.front();
                    if(!q.empty() && out_q == take) q.pop();
                    else que = 0;
                }
                if(pri){
                    out_p = p.top();
                    if(!p.empty() && out_p == take) p.pop();
                    else pri = 0;
                }                
            }
        }
        if(sta == 1 && que == 0 && pri == 0) printf("stackn");
        else if(sta == 0 && que == 1 && pri == 0) printf("queuen");
        else if(sta == 0 && que == 0 && pri == 1) printf("priority queuen");
        else if(sta == 0 && que == 0 && pri == 0) printf("impossiblen");
        else printf("not suren");
}
return 0;
}
 out_s = s.top();
 if(!s.empty() && out_s == take) s.pop();

在这里,您首先访问堆栈的顶部元素,然后才检查堆栈是否真的包含任何内容。

在修改后的代码中,top()调用由empty()和逻辑和保护,因此在容器为空时不会发生。