堆栈和队列奇怪的错误

时间:2014-09-02 17:35:25

标签: c++ stack queue

int main()
{
  char ans = YES;
  Stack card;
  int arr[CARD_PER_DECK];
  int catchVar;//to hode values popped off the stack                                                                        
  int size = 0;
  // put shuffled cards into the stack                                                                                      
  inOrder(arr, CARD_PER_DECK, CARD_NUM_RANGE);
  randomize(arr, CARD_PER_DECK);
  // print(arr, CARD_PER_DECK, card);                                                                                       
  for (int i = 0; i < CARD_PER_DECK; i++){
    card.push(arr[i]);
    cout << arr[i] << " ";
  }
  cout << endl;
  //testing popping                                                                                                         
  for (int i = 0; i < CARD_PER_DECK; i++){
    card.pop(arr[i]);
    cout << arr[i] << " ";
  }
  cout << endl;
  return 0;
}
void swap(int *a, int*b)
{
  int temp = *a;
  *a = *b;
  *b = temp;
}
void randomize(int arr[], int n)
{
  srand(time(NULL));
  for (int i = n-1; i>0; i--){
    int j = rand()%(i+1);
    swap(&arr[i], &arr[j]);
  } 
}
void print(int arr[], int n, Stack card)
{
  for (int i = 0; i < CARD_PER_DECK; i++){
    card.push(arr[i]);
    cout << arr[i] << " " ;
  }
  cout << endl ;
}


//stack.cpp
Stack::Stack()
{//Sets stack to initial empty state                                                                                        
  capacity = 1;
  stackSize = 0;
  stackArray = new int[stackSize];
  top = -1;
}
void Stack::push(int num)
{
  if (stackSize > capacity){
    resize(capacity*2);
  }
  top++;
  stackArray[top] = num;
  stackSize++;
}
void Stack::resize(int newCap)
{
  int* resizeArray = new int[newCap];
  for (int i = 0; i < stackSize; i++)
    resizeArray[i] = stackArray[i];
  capacity = newCap;
  delete[] stackArray;
  stackArray = resizeArray;
}

我试图将随机数放入堆栈并将其弹出。它可以编译,但是当我运行它时我得到了这个错误:在抛出&#39; std :: bad_alloc&#39; what():std :: bad_alloc的实例后终止调用 我是新手,有谁能告诉我如何解决它?

谢谢

1 个答案:

答案 0 :(得分:1)

你应该修复你的push()函数,使用固定数量的元素来增长数组,如下所示:

void Stack::push(int num) {
    static const int grow = 10; // Grow the array for 10 elements a time
    if (stackSize > capacity){
        resize(capacity + grow);
    }
    top++;
    stackArray[top] = num;
    stackSize++;
}