c++ - 使用递归对堆栈进行排序
问题描述
所以我试图对基于数组的堆栈进行排序,但我不断收到以下问题:a.out(11849,0x115ce05c0) malloc: * 对象 0x7fc181402a80 的错误:未分配指针被释放 a.out(11849,0x115ce05c0) malloc: *在 malloc_error_break 中设置断点进行调试。这是我的班级规范
StackType::StackType()
{
maxLength = 10;
Top = -1;
numArray = new int[maxLength];
}
//checks if stack is full
bool StackType::isFull()
{
if(Top == maxLength -1)
return true;
else
return false;
}
//checks if stack is empty
bool StackType::isEmpty()
{
if(Top == -1)
return true;
else
return false;
}
//insert numbers into stack
void StackType::push(int num)
{
if(isFull())
throw FullStack();
Top++;
numArray[Top] = num;
}
//deletes numbers in stack
void StackType::pop()
{
if(isEmpty())
throw EmptyStack();
Top--;
}
//returns number at the top pf the stack
int StackType::top()
{
if(isEmpty())
throw EmptyStack();
return numArray[Top];
}
//prints stack
void StackType::printStack()
{
if(isEmpty())
cout << "Stack is empty\n";
else
{
int tempIndex = 0;
//top is the last position of array
cout << "Printing stack:\n";
while(tempIndex <= Top)
{
cout << numArray[tempIndex] << endl;
tempIndex++;
}
}
}
//deletes array
StackType::~StackType()
{
delete [] numArray;
}
这是我的客户代码
#include "StackType.h"
#include <iostream>
using namespace std;
StackType sortStack(StackType stack, StackType &tempStack);
int main ()
{
//read 10 ints into stack
//output them first
StackType currentStack, orderedStack;
currentStack.push(21);
currentStack.push(49);
currentStack.push(7);
currentStack.push(81);
currentStack.push(5);
currentStack.push(17);
currentStack.push(2);
currentStack.push(26);
currentStack.push(42);
currentStack.push(58);
currentStack.printStack();
cout << "The following is the sorted stack\n";
sortStack(currentStack, orderedStack);
//implement recursion here
//output stack again
return 0;
}
StackType sortStack(StackType stack, StackType &tempStack)
{
int current;
if(stack.isEmpty() && tempStack.isFull()) {
cout << "did it \n";
return tempStack;
}
else
{
current = stack.top();
stack.pop();
if(tempStack.isEmpty())
{
cout << "here1 \n";
tempStack.push(current);
return sortStack(stack, tempStack);
}
else
{
if(current < tempStack.top())
{
stack.push(tempStack.top());
tempStack.pop();
tempStack.push(current);
cout << "here2 \n";
return sortStack(stack, tempStack);
}
else
{
//when current is greater than temp.top
tempStack.push(current);
cout << "here3 \n";
return sortStack(stack, tempStack);
}
}
}
}
解决方案
您StackType
按值传递,这会导致它被复制,但您没有提供复制构造函数。结果,您最终会得到两个实例,StackType
它们都指向同一个数组,并且都试图删除它。第一个成功,另一个触发未定义的行为。
换句话说,您的班级违反了三/五/零规则
推荐阅读
- java - 是否可以在自定义启动器中不显示来自某些应用程序的 android 通知?
- sql-server - 从变量中提取特定字符串
- oclif - 如何强制 --help 命令在 Oclif 的 run 方法中执行
- php - 加入关系导致模型未找到错误
- r - 如何在 r 中应用具有更多数据框的聚合
- windows - 在窗口的任务计划程序上安排任务
- java - 无法通过 Selenium 和 Java 在 https://spicejet.com 中选择出发日期
- swift - 如何在 swift iOS 应用程序中允许 gboard?
- r - 在 ARIMA 或 ETS 预测后为最终结果添加季节性和非平稳性
- android - Android Studio:默认语言