私のクラス割り当てはバイナリツリーを作成することです。ノードのベクトルを使用することにしました。私のコードを実行しようとすると、プロセス11の不正アクセスエラーが発生し、IDE /デバッガ(CLion)は常にノードのクラス宣言をハイライト表示します。コードは以下の通りです。誰も私がなぜこのエラーが発生し続けているのかを教えてもらえますか?無効なメモリアクセスはどこで起こっていますか?C++ EXC_BAD_ACCESS(バイナリツリー)
//Genghis Khan
#include <iostream>
#include <vector>
using namespace std;
//Creating node class and initializing tree vector
class node
{
public:
int key;
double balance;
string name;
friend class binarytree;
bool visited; //for use in traversal
};
class binarytree
{
public:
vector<node> tree;
int index; //index to iterate through the tree
//Constructor
binarytree()
{
node sentinel;
sentinel.key = 0;
sentinel.balance = 0;
sentinel.name = "";
sentinel.visited = false;
tree[0] = sentinel;
}
//Empty
bool empty()
{
return(tree.size() == 1);
}
//set temp to root
void set()
{
index = 1;
}
//create a new node
/*node create()
{
node *v = new node;
cout << "Enter name: ";
getline(cin, v->name);
cout << "Enter balance: ";
cin >> v->balance;
cout << "Enter key: ";
cin >> v->key;
return(*v);
}*/
//return left child for an index
int leftchild(int a)
{
return(a*2);
}
//return right child for an index
int rightchild(int a)
{
return(a*2+1);
}
//whether a node is a leaf
bool isleaf(int a)
{
//if there are no nodes at tree[a]'s left and right children, a is a leaf
try
{
cout << tree[leftchild(a)].key;
cout << tree[rightchild(a)].key;
}
catch(const std::invalid_argument)
{
return true;
}
return false;
}
//insert
void insert(node a)
{
while(!isleaf(index))
{
if(empty())
{
tree[1] = a; //set root to index 1
}
else
{
if(a.key < tree[index].key)
{
index = index * 2;
insert(tree[index]);
}
else if(a.key > tree[index].key)
{
index = index * 2 + 1;
insert(tree[index]);
}
}
}
tree[index] = a;
}
//visit
void visit(node a)
{
cout << a.name << endl;
cout << a.balance << endl;
cout << a.key << endl;
}
//inorder
void inorder(int a) //will only pass root to this function
{
if(!isleaf(a))
{
inorder(leftchild(a));
visit(tree[a]);
inorder(rightchild(a));
}
}
};
int main()
{
int n;
cout << "How many people would you like to enter: ";
cin >> n;
binarytree b;
node *v = new node;
for(int i = 0; i < n; i++)
{
cout << "Enter name: ";
getline(cin, v->name);
cout << "Enter balance: ";
cin >> v->balance;
cout << "Enter key: ";
cin >> v->key;
b.set();
b.insert(*v);
}
for(int j = 0; j < b.tree.size(); j++)
{
cout << b.tree[j].key << endl;
}
return 0;
}
を持っているの例外の詳細 – kvr
'ツリーを共有してくださいする必要があり[0]'は存在しません。 –