This week we learned about different types of linked lists. We can create a linked list with pointers going not only forward, but backwards as well. This makes searching faster.
We also learned about Templates. These are my notes for the “templates” section of that lecture:
A way to write fill in the blanks code, and the blanks are the data types.
Code is often repeated (copy, past, and substitute) because of differences in data type of the parameters.
Templates allow us to write generic code where data type is filled in automatically at compile time.
***NOTE***
need to overload the insertion operator to display your struct/class if you are using a struct/class for a template.
if you need to write a function to print an array and a double you would need to write 2 functions where the only difference is a few keywords.
we first declare a template class:
#include
using namespace std;
template //T is like a blank … When the compiler sees T it
//knows that T needs to be filled in
// you need to modify your function
void printarray(T arr[],int sz){
for(int i=0;i
cout << arr[i] << endl;
}
}
int main(void){
int arr1[5]={5,3,2,1,6};
double arr2[5]={3.3,1.2, 3.14,6.0,7.8};
char arr3[5][10]={“apples”,”oranges”,”banana”,”pears”,”kiwi”};
}
***NOTE***
You cannot use templates in C, only C++
You can also use Templates for Classes.
There are some rules for Template use in Classes.
• If you you’re doing templates, they go in headers.
tlist.h has the code for templates.
If you need multiple templates, you have to declare it as such:
template
you also have to change the declaration a bit:
if your class or struct uses a Template, the compiler doesn’t know the size of the object so it cannot make it so it doesn’t see it.
so when you declare one, you have to declare it as such:
Node* x;
You have to use the angle brackets.
Instead of primitive data types, you can use classes in those angle brackets, but you need to make sure that the operations being used are supported for that class. (copy ctor, overloaded operators, etc)
Another thing to not with templates is that with the given code:
template
struct Node{
TYPE data_;
Node* next_;
};
that template declaration ONLY applies to the struct underneath it.
A Template declaration ONLY applies the NEXT code block ONLY.
SO, each function, class, struct that uses templates, needs to have those declarations before it.
So the class needs to have a template declaration.
The function prototypes in the class header needs to have its data types replaced with the template name.