在队列上的最后一个操作循环中的错误

Bug in the last loop of operations on a queue

本文关键字:循环 错误 操作 最后一个 队列      更新时间:2023-10-16

这是我解决此问题语句的解决方案:http://uva.onlinejudge.org/index.php?option = onlinejudge间

我会遇到运行时间错误,尽管当我使用下面的调试语句时,该程序给出了正确的输出。

while(!q.empty()){
        cn=0;
        while(q.front().first<=ct && cn <=n && q.front().second==cpos){
            allCarT.push_back(ct+t);
            for(i=0; i< sz(allCarT); i++) cout << allCarT[i] << "n"; //debugging statement give correct answers
            q.pop(); //error occurs here in the last loop
            cn++;
        }
        if(cn==0 && q.front().first > ct){
            ct = q.front().first;
        }else{
            ct+=t;
            if(cpos=="left") cpos="right";
            else cpos="left";
        }
    }

完整的解决方案:https://ideone.com/bcu3ut

在该代码中,您不检查队列是空的:

while(q.front().first<=ct && cn <=n && q.front().second==cpos){
    allCarT.push_back(ct+t);
    q.pop(); //error occurs here in the last loop
    // queue can be empty now, so you have out of bound access with q.front()
    cn++;
}