覆盖C++中的对象

Overwriting Objects in C++

本文关键字:对象 C++ 覆盖      更新时间:2023-10-16

我正在为学校做一项作业,该作业使用二叉树实现特定的算法。

我已经计算出了算法,我的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/或者类似的东西。它将为您识别许多无效的内存访问。