Reputation: 75
I've written a linked list which stores informations about students. How can I change it to a template, which could have store ints or any other type? Do I have to overload methods in linked list class, cause now they take 6 arguments? I mean, now the method for inserting at end(for student data) looks like this:
void insertAtEnd(int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty);
And if I want to store ints, it will look like this:
void insertAtEnd(int Data);
So if I want to use templates for adding students and for example integers, should it look like this?
template <class T>
Class llist{
void insertAtEnd(int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty);
void insertAtEnd <T Data>;
}
Here is implementation of student and linkedlist class:
class student {
public:
int index;
string name;
string surname;
int yearOfStudy;
string fieldOfStudy;
string specialty;
student *next; //pointer to next item
student();
};
student::student() {
next = 0;
}
class llist {
public:
void insertAtEnd (int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty);
void insertAtBeginning (int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty);
void insertAtGivenPosition(int a, string n, int index, string name, string surname, int yearOfStudy, string fieldOfStudy, string specialty);
void findStudent(int index, string surname);
void deleteLast ();
void deleteSelected(int index, string surname);
void deleteAll ();
void displayList ();
student *first; //pointer on first elem
llist();
};
Upvotes: 0
Views: 281
Reputation: 1099
make a constructor for the types you want to store and then you only have to send one parameter. Or you could pass in an initializer list for simple objects :-
push( {"student name", "age", major} );
Technically, that's only one parameter, assuming that the fields match the order in the "student" struct/class, so they're only passed as one thing. You can then easily recode the list as a template . Or you call the constructor in the push command:
push( Student("student name", "age", major) );
If you treat the data as a single object then it's easier to convert your list to a generic template because it's no longer closely coupled with the data. The format of the data are details that the data object is supposed to handle.
Upvotes: 0
Reputation: 669
Within the constraints of your question, if it where me, I would change your class structure to:
class student {
public:
int index;
string name;
string surname;
int yearOfStudy;
string fieldOfStudy;
string specialty;
//student *next; //pointer to next item
student();
};
template <class T>
class node {
T data;
node<T> *next;
}
template <class T>
class llist {
public:
void insertAtEnd (const T &data);
.
.
.
private:
node<T> *list;
}
Take a look at the above psuedo code and see how/if it answers your questions.
Upvotes: 1