Okay, so I'm currently learning trees in class right now and decided to self-experiment with some code to kind of understand how trees work and are organized, but I've run into a problem that I do not understand...
So the basic idea is that I'm just making nodes that act as people who have a name, their health (like 92, or 96), and their overall score (like 82, 90, 100), and potential children. Don't mind the variable choices...
I wanted to make a function where the user inputs the data for the person, then if the person has children, recurse through the same function and so on until the choice is not y/Y and the function ends.
By using the vector, I can create dynamic space for however many children the person has (as inputted by user) and can repeat the process using a for loop for every child of the parent, until it reaches a nullptr (if t != nullptr).
By resetting the childrenCount to 0 every time the function recurses, I will be able to create x many new children if the (now main) person has children.
If any of what I 'understand' about trees or vectors is incorrect above, please do correct them >_<, I just also recently learned about vectors and have yet to really implement them in my own functions so I feel a bit lost.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
#include <vector>
#include <iostream>
using namespace std;
struct Node
{
int health;
int overall;
string name;
vector<Node*> children; //Vector for storing children
};
//Function Prototype(s)
void findData(Node* &t);
//int main
int main ()
{
Node* humans = new struct Node; //Tree
findData(humans);
//INCOMPLETE
return 0;
}
void findData(Node* &t)
{
int childrenCount = 0;
char enter;
cout << "Enter the person's name: ";
getline(cin, t->name); //This is where the error occurs
cout << "Enter " << t->name << "'s health: ";
cin >> t->health;
cout << "Enter " << t->name << "'s overall #: ";
cin >> t->overall;
cout << "Does this person have any children? ";
cin >> enter;
if (enter == 'Y' || enter == 'y')
{
cout << "How many children? ";
cin >> childrenCount;
t->children.resize(childrenCount);
for (int i = 0; i < t->children.size(); i++)
findData(t->children[i]);
}
else
cout << "Okay. Finished finding data." << endl;
}
|
The error I receive is at the line where I'm re-entering the data for the children[0]'s name after recursing once. It takes me to this separate place in xcode (which I assume I have yet to learn about) and says the following:
1 2 3 4
|
_LIBCPP_INLINE_VISIBILITY
bool __is_long() const _NOEXCEPT
{return bool(__r_.first().__s.__size_ & __short_mask);}
//Thread 1: EXC_BAD_ACCESS (code=1, address=0x8)
|
Potential problems/ideas I thought might have been the case include
1. Maybe it has to do with the parameter I've chosen?
2. Yeah that's it... I'm clueless
Thanks