【发布时间】:2018-10-13 08:57:09
【问题描述】:
所以我通过将节点放入向量中来创建二叉搜索树 (BST)。这些节点存储3个值,一个用户输入int ID,一个用户输入int年龄,一个用户string输入姓名。
将这些节点插入向量时,它们按升序存储。
目前我正在使用两个节点。
104 10 鲍勃
102 11 史蒂夫
推回第一个节点时,没有问题;但是,当尝试推回第二个节点时,我收到了向量类抛出的 out_of_bounds 错误。
在尝试切换这两个节点的位置时,我认为我的插入函数有问题,但是我无法准确判断问题出在哪里。
#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int index;
struct Node
{
int ID;
int age;
string name;
Node()
{
}
Node(int id, int Age, string nm)
{
this->ID = id;
this->age = Age;
this->name = nm;
}
};
vector<Node> binaryTree;
BST::BST()
{
}
void BST::start()
{
int choice;
cout << "What would you like to do?" << endl;
cout << "1. Add a node to the tree" << endl;
cout << "2. Delete a node from the tree" << endl;
cout << "3. Find a node in the tree" << endl;
cout << "4. Report the contents of the tree" << endl;
cout << "5. Exit program" << endl;
cin >> choice;
if (choice == 1)
{
insert();
}
if (choice == 3)
{
find();
}
if (choice == 4)
{
report();
}
}
void BST::insert()
{
int ID;
int AGE;
string NAME;
cout << "Please enter the ID number, age and name" << endl;
cin >> ID >> AGE >> NAME;
Node *tree = new Node(ID, AGE, NAME);
if (index == 0)
{
binaryTree.push_back(*tree);
index++;
}
if (index > 0)
{
if ((binaryTree.at(index - 1).ID) < ID)
{
binaryTree.push_back(*tree);
index++;
}
}
if (index > 0)
{
if ((binaryTree.at(index - 1).ID) > ID)
{
Node *temp = new Node();
*temp = binaryTree.at(index - 1);
binaryTree.at(index - 1) = *tree;
binaryTree.at(index) = *temp;
index++;
}
}
cout << "Added! Size: " << binaryTree.size() << endl;
cout << " " << endl;
start();
不胜感激!谢谢!
【问题讨论】:
-
你的节点不应该持有 2 个节点吗?
-
@ZivS - 这是
i的孩子是2*i和2*i + 1的表示。因此向量 -
您正在泄漏内存。您动态分配一个对象,将对象复制到向量中,然后在函数结束时丢失原始对象。你也在
if中做类似的事情。简单地摆脱指针和动态分配将修复内存泄漏。 -
如果它使用不同的数据结构,它会,但它被存储在一个向量中,它并不完全“需要”它。至少这是我的假设
-
1) 不就是错字吗:
binaryTree.at(index - 1) = *tree; binaryTree.at(index) = *temp;(注意第二个at)?由于index包含vector中的元素数量(我认为没有意义,因为std::vector具有size方法),最大有效索引为index - 1。 2) 你在所有这些new调用中泄漏内存,而没有deleteing 你new。
标签: c++ vector nodes indexoutofboundsexception push-back