Lab3 PDF
Lab3 PDF
iulia.stanica@gmail.com
Template functions
Template classes
Stack
Using headers
Applications of stack
Info: Sorting algorithms
Generic programming
Allows a function or class to work on many
different data types without being rewritten
for each one
A function template allows any type of data (T)
for its arguments
Syntax:
template <typename T>
T functionName(T a, T b)
{
// code
}
typename can be replaced with class
Ex:
template <typename T>
T maxim(T a, T b) {
return a > b ? a : b; //if a>b return a, else, b
// equivalent to: if (a>b) return a; else return b;
}
Create objects:
mypair <int> object (25, 13);
Example with 2 fields:
We create objects:
◦ KeyValue <int, char> obj (12, ‘c’);
Change the class Point from the previous lab
by using templates (the x and y coordinates
are of type T). Test the class using float and
int coordinates.
Write a template function to sort an array of 5
elements. Write a different template function for
swapping 2 values of the array. Read the values
from keyboard.