覆盖C++中的对象
Overwriting Objects in C++
我正在为学校做一项作业,该作业使用二叉树实现特定的算法。
我已经计算出了算法,我的main()在第一次迭代中正确运行,但在那之后seg就会出错(你应该能够连续运行程序并模拟算法,而不必再次运行./main
,因此出现while循环)。
我有一种感觉,这与我的BinaryTree *tree
在第一轮中被创建和使用有关,然后在没有被释放的情况下被再次使用,但我试图解决这个问题的努力没有结果。
以下是我的主要问题:
#include <iostream>
using namespace std;
#include "BinaryTree.h"
/* Prompts user to pick an option:
* first fit, best fit, or quit
*/
int main (){
bool quit;
int command, elements, binSize, x, totalNodes;
cout<<"Welcome to assignment 6!"<<endl;
BinaryTree *tree = new BinaryTree();
//Declare new tree for use in first fit algorithm
while (!quit)
{
cout<<"Choose an option for the test: 1-> First fit, 2-> Best Fit, 3-> Quit"<<endl;
cin>>command;
/**************
First Fit
**************/
if(command==1)
{
cout<<"First Fit!n";
cout<<"Enter number of objects: ";
cin>> elements;
cout<<"Enter capacities of bins: ";
cin>> binSize;
cout<<"n";
x=1;
while (elements > x) //Get next highest power of 2
x=x*2; //to fill out bottom of binary tree
totalNodes = 2*x -1;
for(int i=1; i<=totalNodes; i++)
{
//cout<<"Adding node: "<<i<<endl;
tree->AddItem(i, -1);
}
bool done = false;
//elements = x;
int a[elements];
for (int i=1; i<=elements; i++)
{
cout<<"Enter space requirement of object "<<i<<endl;
cin>>a[i];
}
for (int i=1; i<=elements && !done; i++)
{
tree->Insert(a[i], binSize, elements);
}
//Loop done, seg faults happens when called again
}
BinaryTree.cpp文件有点长,所以如果需要,我会将它们链接到这里:http://pastebin.com/EtwdBp8N
任何关于不良行为的建议或信息都将不胜感激。
int a[elements]; for (int i=1; i<=elements; i++) { cout<<"Enter space requirement of object "<<i<<endl; cin>>a[i]; }
这个位是错误的,数组在C/C++中是基于零的,循环应该是:
for (int i=0; i<elements; i++)
如果调试器没有帮助,请尝试使用valgrind运行程序http://valgrind.org/或者类似的东西。它将为您识别许多无效的内存访问。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象