How can I make a tree with n number of child nodes? - c++

Usually they have only two, but I need to make an object were there are a random number of pointers.
To represent this image enter image description here
Using what I know I made this:
struct tree{
string name;
list<struct pointer> pointers,
tree(int x){
name= x;
pnext=null;
}
} root1;
struct pointer{
struct tree *pnext;
};
A tree or object with a list of pointers and the structure for the pointers, but I doesn´t seem right.
How can I make a tree with a random number of pointers?
(I should say what is wrong with but I don´t een know were to start, sorry)

try this:
#include <vector>
struct person {
string name;
vector<person> children;
person(string iName, vector<person> iChildren) {
name = iName;
children = iChildren;
}
}
This way, each person has a name, and a vector with all of it's children in it.

Related

From Vector to Linked List C++

I am pretty new with C++ and I wanted to make sure that I have set up my linked list currently. The information was stored in a vector before, but I was assigned to change it to a linked list. The information stored is CandidateInfo, here is the original code. Have I set my list up correctly?
struct CandidateInfo {
std::string name;
int votesInThisState;
int delegatesWonInThisState; };
std::vector<CandidateInfo> stateCandidates;
And here is my attempet. Suggestions welcomed.
template <typename StatePrimary>
struct CandidateInfo
{
std::string name;
int votesInThisState;
int delegatesWonInThisState;
StatePrimary state;
CandidateInfo<StatePrimary>* next;
CandidateInfo()
{
next = 0;
}
CandidateInfo
(const StatePrimary& c,
CandidateInfo<StatePrimary>* nxt =0)
: state(c), next(nxt)
{}
};
template <typename StatePrimary>
struct CandidateInfoHeader
{
CandidateInfo<StatePrimary>* first;
CandidateInfoHeader();
};
I would have put this as a comment, but I don't have enough reputation yet. Is there a reason you're not using a std::list? That way you could use the code in the first snippet you posted, i.e.:
struct CandidateInfo {
std::string name;
int votesInThisState;
int delegatesWonInThisState; };
std::list<CandidateInfo> stateCandidates;
(Note the change from vector to list in the last line)
std::list is an STL implementation of a doubly linked list.

Nested data structure with Linked list

I have studied many example related to linked list example but they just explain in simple way using only one structure type. So i need to dig more to clear my doubts:
struct movies_t {
int number;
string title;
int year;
movies_t *next;
}
Does all of the nodes of a linked list necessarily should be of movies_t type (as its in array:array is a collection of values of similar type) ?
If i want to add a one or several more different new structure dynamically and those contains completely different elements except the int number; which is a common element in all data structure to sort data orderly. Is it possible ?
If I have to implement nested data structures(given below), would it be possible to do it with Linked list or with some tree data structure (Binary, B, B+ trees )?
struct movies_t {
int number;
string title;
int year;
}
struct friends_t {
int number;
string name;
string email;
movies_t favorite_movie;
}
struct world_t {
int number
string country;
string continent;
double population
movies_t favorite_movie;
friends_t friends_forever;
}
You can create a class rather structure for node. Do the following,
class parent_t{
int number;
parent_t* next;
}
class movies_t: public parent_t {
string title;
int year;
}
class friends_t : public parent_t {
string name;
string email;
movies_t favorite_movie;
}
class world_t: public parent_t {
string country;
string continent;
double population
movies_t favorite_movie;
friends_t friends_forever;
}
Now, you can create the linked-list of parent_t type. Then you can insert the movie_t, friends_t, world_t type objects into the linked-list.

C++ print a linked list

I'm new to c++ and am having problems with my print function.
This might be a really simple problem but I can't find out how to solve it.
Before I start to write the code I might add that this is supposed to be a circular list.
First of all, here is my linked lists structure
struct CL;
typedef CL* list_type;
struct person
{
string last_name;
string first_name;
string tel_nr;
};
struct CL
{
person data;
list_type next;
};
As you can see, I want the list to contain a data and a pointer. The data is a person(last name, first name and telephone number(as a string)).
My main program look like this
int main ()
{
list_type list;
list_type first;
string line;
person info;
ifstream myfile ("INFILE.TXT");
if (myfile.is_open())
{
while (myfile.good())
{
getline (myfile,line,',');
info.last_name=line;
getline(myfile,line,' ');
getline(myfile,line,':');
info.first_name=line;
getline(myfile,line);
info.tel_nr=line;
if(first==0)
{
list = new CL;
first = list;
list->data = info;
list->next = 0;
}
else
{
list->next = new CL;
list = list->next;
list->data = info;
list->next = 0;
}
}
list->next = first;
print(list);
myfile.close();
}
else cout<<"Unable to open file.";
return 0;
}
and now to the part where I am having problems, the print function.
void print(CL* cur)
{
list_type first;
first=cur;
int x;
do
{
cout<<"\n"<<"Your Data is: ";
cout<<cur->data.last_name<<cur->data.first_name<<cur->data.tel_nr;
//I guess this is where the fault lies ^.
cur = cur->next;
}
while(cur != first);
}
If possible I would love an explanation, not just the correct code.
Thanks
Edit.
The result I am getting is alot of weird characters like:
ê,(,?,ý and alot of other characters I don't know how to type.
The result I am expecting is something like this
Robertson Linda 0838-2345
Brown Charles 068-24567
etc until the end of list
Edit2.
Solved, thx alot.
First problem
int main ()
{
list_type list;
list_type first; // uninitialized value
// ...
if(first==0) // ???
{
You need to initialize first explicitly for this to do what you expect:
int main ()
{
list_type list;
list_type first = 0;
// ...
if(first==0)
{
Second problem
Your linked list code is fragile in the first place because you're not really writing (idiomatic) C++. Even without using the STL, your list can (and should) provide some degree of abstraction. It's actually easier to write it properly, because your data structure logic doesn't get all mixed up with your test-harness or problem domain logic.
For example,
class PersonList {
CL *head;
CL *tail;
public:
PersonList(); // think about how to initialize an empty list
void push_back(Person const&); // head & tail modified in here
// etc.
};
Note that if you're not allowed to use class, this is identical:
struct PersonList {
private:
CL *head;
// ... as above ...
and if you're not allowed to use constructors & methods at all, a good C-style equivalent might be:
struct PersonList {
CL *head;
CL *tail;
};
struct PersonList * new_list();
void push_back(struct PersonList *, Person const &);
this still groups your data structure code in one place, away from your business logic/problem domain/test harness code.
Initialize first to zero. You're getting bad characters because the first link isn't initialized.

the "this" pointer in classes accessing vector elements

I have the following in an implementation file...
void ClientList::interestCompare(vector<string> intr)
{
for(int index = 0; index < intr.size(); index++)
{
this->interests[index];
}
}
and this in the specification file...
class ClientList
{
private:
// A structure for the list
struct ListNode
{
char gender;
string name;
string phone;
int numInterests; // The number of interests for the client
vector<string> interests; // list of interests
string match;
struct ListNode *next; // To point to the next node
};
//more stuff
...}
is it possible to use the "this" pointer to access the "interests" vector in the struct?
If so how.
As I have it now, I initialize a ListNode pointer to head in order to access the list. I'm just wondering if the "this" pointer can only access members of the class, or if they can access deeper ADT variables embedded in the class.
Does that question even make sense?
You only declared a ListNode type inside ClientList class which doesn't mean you have a instance of ClientList. As you hare using std::vector already, you could use std::vector or std::list instead of implementing another list
class ClientList
{
private:
// A structure for the list
struct Client
{
char gender;
std::string name;
std::string phone;
int numInterests; // The number of interests for the client
std::vector<string> interests; // list of interests
std::string match;
};
std::vector<Client> clients;
//more stuff
};
Edit:
If you want to compare two lists, use std::set_intersection, it requires two containers to be sorted in place.
void ClientList::FindClientHasCommonInterest(const vector<string>& intr)
{
for(auto client = clients.begin(); client != clients.end(); ++client)
{
std::vector<std::string> intereste_in_common;
std::set_intersection((*client).begin(), (*client).end(),
intr.begin(), intr.end(),
std::back_inserter(intereste_in_common));
if (intereste_in_common.size() >= 3)
{
// find one client
}
}
}
No, it's different between Java and C++ for nested class. C++ nested class is essentially the same as static nested class in Java. So, you have to use an instance of the nested struct to access its member.

Accessing another classes member

I have the following
class book
{
friend class linkedList;
private:
class student
{
friend class book;
string name;
string number;
string gpa;
student *left;
student *right;
student(string name1, string number1, string gpa1,
student *left1 = NULL, student *right1 = NULL)
{
name = name1;
number = number1;
gpa = gpa1;
left = left1;
right = right1;
}
};
int count;
student *root;
ofstream recordBook;
void _add(student *&, string, string, string);
void _display_book(student *);
bool _search_for_name(string, string&, string&);
bool _edit_entry(string &name, string &edited_number);
void _del_person(student *&, string);
void _save(student *root);
void _del_Tree(student *);
public:
student *currentRoot;
book(void); //Constructor
~book(void);//Destructor
void add(string entry_name, string telephone_number, string gpa);
void display_book();
bool search_for_name(string find_name);
bool edit_entry(string entered_name, string edited_number);
void del_person(string entry_name);
void save();
void load_data();
};
class linkedList
{
friend class book;
int someInt;
struct node
{
public:
string key;
node *link;
node *link2;
} *pointer;
public:
student book::*currentRoot = &book::currentRoot;
linkedList();
~linkedList();
void append(string &str);
void del(string &str);
void display();
};
And I need to make a pointer to "student *currentRoot" from my linkedList classes function.
void linkedList::append(string &str)
{
node *q, *t;
if(pointer == NULL)
{
pointer = new node;
pointer->key = str;
pointer->link = NULL;
pointer->link2 = currentRoot;
someInt += 1;
}
else
{
q = pointer;
while(q->link != NULL)
{
q = q->link;
}
t = new node;
t->key = str;
t->link = NULL;
q->link = t;
someInt += 1;
}
}
In linkedList::append I need to make link2 point to where currentRoot is pointing to. How can I do this? (currentRoot is already set to point at a node in a binary tree. Just gotta get my hash table to also point there.) Thanks for any help.
In comments you said:
In the simplest terms I can think of... I am trying to get a pointer in one class to point to another pointer in a different class.
To answer that question: an inner class has no special relationship to the outer class. For example, a student instance within the book class has no direct way to access its “containing” class.
To do this you would have to pass a pointer to the containing book class into student’s constructor and store it in an instance variable within student.
However, this has a big caveat: when the student instance holds a pointer to the containing book class, that pointer could become invalid. For example, if you are storing book instances in a container like a std::vector, the vector may reallocate memory, invalidating any pointers to books held within the vector.
If you can guarantee that the book will not be stored in an STL container (or anywhere else where it can get moved) then this approach can work.
I would still reconsider the overall approach as having instances store pointers in this way seems fragile. There could be a composition-based approach that would work.
The use of friend is suspect.
Typical object-oriented programming dictates that a linked list container class should only deal with pointers to class objects, and should not know about or deal with anything within the class objects themselves.
If the contained class does need to expose information about itself (i.e., any of its members), it should provide public accessor functions for doing so.
I agree with what others commented about code, so I won't repeat it and just point to invalid syntax in your code:
public:
student book::*currentRoot = &book::currentRoot;
1) the pointer to member is not what you wanted, it should have been:
public:
book::student* book::*currentRoot;
2) you cannot assign to non-static member in class definition. It's only allowed for static members of integral type. But you can assign to it somewhere where you have an object:
void foo()
{
linkedList l;
l.currentRoot = &book::currentRoot;
}