Вы находитесь на странице: 1из 31

Object Oriented Programming

Lecture #11 Elhanan Borenstein borens@tau.ac.il

copyrights Elhanan Borenstein

Agenda
Template Functions and Classes A (very) Short Reminder Inheriting Template Classes Introduction to STL
General Containers Iterators Object Functions STL Examples

copyrights Elhanan Borenstein

Template Functions / Classes


A (very) Short Reminder
template<class T> void Swap(T& a, T& b) { T temp = a; a = b; b = temp; } template<class T> class Array { T* arr; int size; public: Array(int s) : size(s), arr(new T[size]) {} T& operator[](int index) {return arr[index];} };
copyrights Elhanan Borenstein

void main() { int i=4, j=9; Swap(i, j); char* str1 = hello; char* str2 = world; Swap(str1, str2); Array<int> iArray(10); Array<float> fArray(10); iArray.Print(); fArray.Print(); }

Inheriting Template Classes

copyrights Elhanan Borenstein

Inheriting Template Classes


Introduction
Template classes can be inherited according to the standard inheritance guidelines. Inheritance can use two approaches (both very common):
The derived class is not a template. The actual type will be defined when inheriting. class ExtendedIntArray : public Array<int> The derived class is by itself a template class. No need to specify the type when inheriting. template<class T> class ExtendedArray : public Array<T>

copyrights Elhanan Borenstein

Inheriting Template Classes


A Class Derived from Template Class
If while inheriting the template class, we specify all the parameters of the template class, we will actually create a new regular (non-template) class.
Example: ExtendedIntArray

A Template Class Derived from a Template Class


While inheriting the template class, we leave the templates parameters undefined. That will in effect cause the derived class to become a template class.
Example: extintarray.cpp

copyrights Elhanan Borenstein

Try This
Example: temptemp.cpp
I'm class A<int> I hold int The inner value is: 9 I'm class B<class A<int> > I hold class A<int> The inner value is: I'm class A<int> I hold int The inner value is: 9

I'm class A<int> I hold int The inner value is: 9

copyrights Elhanan Borenstein

Exercises
or, An introduction to the STL introduction

copyrights Elhanan Borenstein

Exercise 1
Implement a generic Find() function, which gets:
a pointer to the beginning of an array a pointer to the end of an array the value to search for

The function returns the address of the first items in the array that is equal to the given value or the address of one location after the last item if the value was not found.
template<class T> T* Find(T* begin, T* end, T value) { while (begin != end) if (*begin == value) return begin; else begin++; return begin; }
copyrights Elhanan Borenstein

void main() { int array[ ] = {3,2,5,7,2,8,11}; int* j = Find (array, array + 6, 7); }

Exercise 2.1
Implement a class called Sqr which will include only one thing:
an overloading of the operator () which will get as a parameter T& and will assign to it its square value.
class Sqr { public: template<class T> void operator() (T& t) { t = t*t; } }; void main() { Sqr MySqrMachine; int i = 2; float f = 3.25; MySqrMachine(i); MySqrMachine(f); }

This is called an Object Function.

copyrights Elhanan Borenstein

Exercise 2.2
Implement a general DoIt fucntion which gets:
a pointer to the beginning of an array a pointer to the end of an array A reference to an object

The function should go over all elements of the array and send each element to the () operator of the object it got.
template<class T, class G> void DoIt(T* begin, T* end, G& Obj) { while (begin != end) { obj(*begin); begin++; } }

copyrights Elhanan Borenstein

Exercise 2.all
Putting it all together
class Sqr { public: template<class T> void operator() (T& t) { t = t*t; } }; void main() { int array[ ] = {1,5,7,8,3,2,9,2,12}; DoIt(array, array + 8, Sqr()); } template<class T, class G> void DoIt(T* begin, T* end, G& Obj) { while (begin != end) { obj(*begin); begin++; } }

AMAZING !!!!
DoIt() is completely general: It doesnt know the array type. It doesnt know the action it is doing

copyrights Elhanan Borenstein

Food for Thoughts


Imagine a template class
template <class T> class MyClass { T t; };

We wish that all instances of MyClass will be friends...


friend MyClass<T> ??? friend MyClass<G> ???(and than template<class T, class G>)

What if a regular (non-template) class A wishes to give friendship to all instances of MyClass? Whats the meaning of all that???
copyrights Elhanan Borenstein

Introduction to STL (General Algorithms, Containers and Iterators)

copyrights Elhanan Borenstein

A General Find Function


Lets recall the general Find function we saw:
Implement a generic Find() function, which gets:
a pointer to the beginning of an array a pointer to the end of an array the value to search for

The function returns the address of the first items in the array that is equal to the given value or the address of one location after the last item if the value was not found.
template<class T> T* Find(T* begin, T* end, T value) { while (begin != end && *begin != value) begin++; return begin; } void main() { int array[ ] = {3,2,5,7,2,8,11}; int size=sizeof(array)/sizeof(array[0]); int* found; found = Find (&array[0], &array[size], 7); if (found != &array[size]) cout<<FOUND!!!<<endl; }
copyrights Elhanan Borenstein

Can Find() work on a linked-list?

A General Find Function


Now lets enhance this function:
template<class iterator, class T> iterator Find(iterator begin, iterator end, const T& value) { while (begin != end && *begin != value) begin++; return begin; } } void main() { int array[ ] = {3,2,5,7,2,8,11}; int size=sizeof(array)/sizeof(array[0]); int* found; found = Find (&array[0], &array[size],7); if (found != &array[size]) cout<<FOUND!!!<<endl;

What restrictions does Find pose on the parameters? Why do we use two types in the template? Can Find() work on other data structure other than arrays?

copyrights Elhanan Borenstein

Iterators
Introduction & Concepts
It appears that Find() can still work only on arrays, as we are using begin++ to iterate the items. BUT suppose our data-structure implanted an additional iterator class. This class will support the followings:
Represent an object that can point to an item in our data structure. Overload the operator *, so that using *iter will return the item. Overload the operator ++ by advancing to point on the next item. Overload the operator ==/!= to compare whether two Iterators points to the same item. Overload the casting operator to allow casting to item*. The iterator class, behaves just like a pointer to data item (item*), although it is actually a completely separate class.
copyrights Elhanan Borenstein

Link List Example


Class item<T> Class list<T>
head tail

Class list<T>::iterator

data Class T / / / /

data

data

data

Example: link_list
copyrights Elhanan Borenstein

copyrights Elhanan Borenstein

General Containers and Iterators


So, what do we have so far?
A list<T> class that can store a link list of any data type
list<int> list<float> list<Employee> and many more

A general Find() function that can find an item in any data structure (providing an iterator implementation) holding any data type
Array<int>, Array<float>, list<int>, list<float>, list<Employee> Tree<int>, Tree<Employee>, Tree<string> and many more

copyrights Elhanan Borenstein

Object Functions
Whats Next?
Lets try to use the same mechanism to send the entire data structure to a template function Apply() which will perform a certain operation/transformation on all the items of the DS Again, we wish that:
Apply() will work with any data structure (implementing iterators). The data structure can store any data type. Apply() will support any operation we wish !!!

Object Functions

copyrights Elhanan Borenstein

Object Functions
Introduction
Our Apply() function will get:
begin iterator end iterator operation.

In C, when we wanted to send an operation as a parameter, we used a function pointer. In C++, we will naturally, use an Object.

copyrights Elhanan Borenstein

Object Functions
sqr.h
struct Sqr { template<class T> void operator() (T& number) const { t = t*t; } };

main.cpp
#include sqr.h #include print.h void main() { Sqr MySqrMachine; Print MyPrintMachine; int i = 2; float f = 3.25; Employee em(John, 3000); MySqrMachine(i); MySqrMachine(f); MyPrintMachine(i); MyPrintMachine(em); }

print.h
struct Print { template<class T> void operator() (const T& printalbe) const { cout<<printable<<endl; } };

copyrights Elhanan Borenstein

Object Functions
Guidelines
Struct is used, as the entire class is public. Note the format of the operator () What restrictions are posed on the parameters send to these object functions?
struct Reverse { template<class T> void operator() (T& reversable) const { reverse(reversable.begin(), reversable.end()); } }; void main() { string str = dlrow olleH; Reverse rev; rev(str); }

copyrights Elhanan Borenstein

Object Functions
and now
Putting is all together example: apply

copyrights Elhanan Borenstein

STL

copyrights Elhanan Borenstein

STL
Introduction
The classes, and algorithms we saw in the previous slides are actually a simulation of the way STL classes, containers and algorithms work. and now for a brief overview of what STL really includes. In general STL includes the following components:
Data Structures (vector, list, set, ) Generic Algorithms (for each, find, sort, ) Object Functions Allocators

copyrights Elhanan Borenstein

STL
Data Structures
STL provides the following data structures:
vector dynamic array (supporting resizing) deque a queue or a stack list doubly linked list map Hashtable (key, value pairs) multimap Hashtable, supports numerous values stored with each key set Hashtable, storing keys only. Each key can only be stored once multiset Hashtable, storing keys only. Each key can be stored several times

All DS supports: begin(), end(), insert(), erase(), clear(...)


copyrights Elhanan Borenstein

STL
Generic Algorithms
All algorithms appear in the header file <algorithm> Include: for_each (analog to our Apply()), find, find_if, count, replace, copy, sort, reverse and many more.

Object Functions
Commonly used with STL. Include: pow, sqrt, sin, other math functions, complex numbers functions, logic functions, comparison functions and many more.

copyrights Elhanan Borenstein

STL - Examples
Example : STL1.cpp
Names: {She Sells Sea Shealls by the Sea Shore } Number of names starts with S = 6

Example : STL2.cpp (merging a vector and a list)


Numbers Vector { 4 7 8 10 14 16 67 123 } Numbers List { 0 1 2 3 4 5 6 7 } Numbers Deque (merged) { 0 1 2 3 4 4 5 6 7 7 8 10 14 16 67 123 }

copyrights Elhanan Borenstein

Questions?

copyrights Elhanan Borenstein

Вам также может понравиться