【问题标题】:terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc"在抛出 'std::bad_alloc' what(): std::bad_alloc 的实例后调用终止
【发布时间】:2017-06-12 04:14:36
【问题描述】:

这个错误的原因是什么?其实我不想受到之前测试用例结果的影响,所以在测试用例开始时,我清空了队列,以便每个测试用例都能重新开始。 "

#include <iostream>      
#include <queue> 
using namespace std;   
int main()
{
queue <int> first;
queue <int> empty;
queue <int> second;
int i,j,k,l,n,m,a,p,q;
int test,t;
std::cin>>test;
t=test;
  while(test--)
     {

        swap(first,empty);
        swap(second,empty);

       std::cin>>n>>m;
       a=2*n;
         for(i=1;i<=a;i++)
                 {
                    first.push(i);
                 }
          for(i=a+1;i<=m;i++)
                   {
                     second.push(i);
                   }
       for(i=1;i<=a;i++)
             {
               p=second.front();
                second.pop();
                   cout<<p;
              q=first.front();
                  first.pop();
                     cout<<q;
              }

   }
 }      

【问题讨论】:

  • 考虑到你有很多 cin 调用,当 bad_alloc 被抛出时你提供的输入是什么?为 n 或 m 提供足够大的值会导致 bad_alloc。
  • 您创建了一个first.front and first.pop() 并且您不首先检查队列是否为空。也检查第二个。阅读 cppreference 上的队列,它可能会对您有所帮助。 [链接]cplusplus.com/reference/queue/queue/pop

标签: c++


【解决方案1】:

这里的问题在于行,

swap(first, empty);
swap(second, empty);

当第一个交换被调用时,'empty' 得到 'first'(并且 'first' 变成 'empty')。现在,当调用第二个交换时,empty 不再是空的(它有“第一个”)。

为了解决这个问题, 一种解决方案可能是,

first = queue<int> ();
second = queue<int> ();

清空队列。

另一种解决方案可能是写,

first = empty;
second = empty;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    相关资源
    最近更新 更多