Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
#include <iostream> using namespace std; //-------------------------------------------------------------template <class T> //function template T abs(T n) { return (n < 0) ? -n : n; } //-------------------------------------------------------------int main() { int int1 = 5; int int2 = -6; long lon1 = 70000L; long lon2 = -80000L; double dub1 = 9.95; double dub2 = -10.15; //calls instantiate functions cout << "\nabs(" << int1 << ")=" << abs(int1); //abs(int) cout << "\nabs(" << int2 << ")=" << abs(int2); //abs(int) cout << "\nabs(" << lon1 << ")=" << abs(lon1); //abs(long) cout << "\nabs(" << lon2 << ")=" << abs(lon2); //abs(long) cout << "\nabs(" << dub1 << ")=" << abs(dub1); //abs(double) cout << "\nabs(" << dub2 << ")=" << abs(dub2); //abs(double) cout << endl; return 0; }
Exercise 1
Write a template function that returns the average of all the elements of an array. The arguments to the function should be the array name and the size of the array (type int). In main(), exercise the function with arrays of type int, long, double, and char.
Class Templates
The template concept can be extended to classes. Class templates are generally used for data storage (container) classes.
#include <iostream.h> using namespace std; const int MAX = 100; //size of array //////////////////////////////////////////////////////////////// template <class Type> class Stack { private: Type st[MAX]; //stack: array of any type int top; //number of top of stack public: Stack(){ top = -1; } //Constructor void push(Type var){ st[++top] = var; } //put number on stack Type pop(){ return st[top--]; } //take number off stack };
Lists
// constructing lists #include <iostream> #include <list> using namespace std; int main () { // constructors used in the same order as described above: list<int> first; // empty list of ints list<int> second (4,100); // four ints with value 100 list<int> third (second.begin(),second.end()); // iterating through second list<int> fourth (third); // a copy of third // the iterator constructor can also be used to construct from arrays: int myints[] = {16,2,77,29}; list<int> fifth (myints, myints + sizeof(myints) / sizeof(int) ); cout << "The contents of fifth are: "; for (list<int>::iterator it = fifth.begin(); it != fifth.end(); it++) cout << *it << ' '; cout << '\n'; return 0; }
Final Exercise
Start with a list of int values. Use two normal (not reverse) iterators, one moving forward through the list and one moving backward, in a whileloop, to reverse the contents of the list.You can use the swap()algorithm to save a few statements. (Make sure your solution works for both even and odd numbers of items.) To see how the experts do it, look at the reverse() function in your compilers algorithm header file.
Checked By: