Presentation is loading. Please wait.

Presentation is loading. Please wait.

© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.

Similar presentations


Presentation on theme: "© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0."— Presentation transcript:

1 © Copyright Eliyahu Brutman Programming Techniques Course Version 1.0

2 © Copyright Eliyahu Brutman Chapter 11 – Templates And STL Version 1.0

3 © Copyright Eliyahu Brutman Templates And STL - 3 Motivation A function for finding minimum value int min(int a, int b) { return (a>b ? a : b) } This is good for integers For floats we will need another function float min(float a, float b) { return (a>b ? a : b) } Can we parameterize this function with a type? Towards Generic Programming Like objects are generalized into classes, we would like to generalize classes and functions into templates.

4 © Copyright Eliyahu Brutman Templates And STL - 4 Motivation Even creating a macro out of it will not work in certain cases #define min(a, b) ((a)>(b) ? (a) : (b)) It will work for min(5, 10); min(5.0, 10.0) Think of an example when it will not work …

5 © Copyright Eliyahu Brutman Templates And STL - 5 Function Template Preserving the semantics of a function Automatically generated instance of a function, varying by type The programmer parameterizes all or a subset of the types in the interface The function implementation remains invariant over a set of function instances, each handling a unique data type template Type min(Type a, Type b) { return ( a>b ? a : b); } Template parameter List

6 © Copyright Eliyahu Brutman Templates And STL - 6 Template Syntax template This line states that everything in the following declaration or definition is under the subject of the template. In the brackets goes a list of “ placeholders variables. ” In almost all cases, they will be specified with either the typename or class keywords. Placeholder variables have one value within each template declaration. Think of them as being replaced by whatever type you specify the template to be.

7 © Copyright Eliyahu Brutman Templates And STL - 7 Class Templates Creating a class, where a type or value is parameterized Motivation A bag (of what?) How would we implement generic code for this problem?  An array of pointers to base class  Each type would have to inherit from the basic type  May be a problematic solution Homogeneous vector can be achieved by a template solution  The template class defines a bag of elements once, in a general way  Programs using bags can instantiate separate bag classes for specific types of elements as necessary

8 © Copyright Eliyahu Brutman Templates And STL - 8 Problem Solution: Templates Template class for a data structure uses a.h file and, instead of a.cpp file, a.template file When an object of a data structure type is instantiated, the type of data object it stores is specified If the class for that object does not already exist, the class is instantiated at compile time Then the object from that class is instantiated

9 © Copyright Eliyahu Brutman Templates And STL - 9 Bags With and Without Templates // BagOfItems.h (Topic 6) #define CAPACITY 50 typedef ExistingClassName Item; class BagOfItems { public: BagOfItems( ); BagOfItems(unsigned int max_capacity); ~BagOfItems( ); // cont ’ d.. // Bag.h (template class) #define CAPACITY 50 template class Bag { public: Bag( ); Bag(unsigned int max_capacity); ~Bag( ); // cont ’ d..

10 © Copyright Eliyahu Brutman Templates And STL - 10 Bags With and Without Templates // … BagOfItems.h cont ’ d bool add( Item * value ); Item * getOne( ); bool isEmpty( ) const; bool isFull( ) const; unsigned int currentSize( ) const; unsigned int capacity( ) const; // cont ’ d.. // … Bag.h cont ’ d (template) bool add( Item * value ); Item * getOne( ); bool isEmpty( ) const; bool isFull( ) const; unsigned int currentSize( ) const; unsigned int capacity( ) const; // cont ’ d..

11 © Copyright Eliyahu Brutman Templates And STL - 11 Bags With and Without Templates // … BagOfItems.h cont ’ d private: unsigned int m_size; unsigned int m_max_capacity; Item ** m_container; }; // end of BagOfItems.h // … Bag.h cont ’ d (template) private: unsigned int m_size; unsigned int m_max_capacity; Item ** m_container; }; #include "Bag.template" // end of Bag.h

12 © Copyright Eliyahu Brutman Templates And STL - 12 Bags With and Without Templates Differences between.template,.cpp files: Occurrences of BagOfItems :: are replaced by Bag :: Member functions, constructors, destructor are preceded by template Constructors are Bag; destructor is ~Bag Assumption: Item is a class See use of NULL in add, getOne

13 © Copyright Eliyahu Brutman Templates And STL - 13 Bags With and Without Templates // BagOfItems.cpp #include “ BagOfItems.h ” #include // continued on next slide // Bag.template #include “ Bag.h ” #include // continued on next slide

14 © Copyright Eliyahu Brutman Templates And STL - 14 Bags With and Without Templates BagOfItems :: BagOfItems( ) { m_max_capacity = CAPACITY; m_size = 0; m_container = new Item* [CAPACITY]; srand( (unsigned int) time( NULL ) ); } // cont ’ d.. template Bag :: Bag ( ) { m_max_capacity = CAPACITY; m_size = 0; m_container = new Item* [CAPACITY]; srand( (unsigned int) time( NULL ) ); } // cont ’ d..

15 © Copyright Eliyahu Brutman Templates And STL - 15 Bags With and Without Templates BagOfItems :: BagOfItems(unsigned int max_capacity) { m_max_capacity = max_capacity; m_size = 0; m_container = new Item*[m_max_capacity]; srand( (unsigned int) time( NULL ) ); } // cont ’ d.. template Bag :: Bag (unsigned int max_capacity) { m_max_capacity = max_capacity; m_size = 0; m_container = new Item*[m_max_capacity]; srand( (unsigned int) time( NULL ) ); } // cont ’ d..

16 © Copyright Eliyahu Brutman Templates And STL - 16 Bags With and Without Templates BagOfItems :: ~BagOfItems( ) { delete [ ] m_container; } // cont ’ d.. template Bag :: ~Bag( ) { delete [ ] m_container; } // cont ’ d..

17 © Copyright Eliyahu Brutman Templates And STL - 17 Bags With and Without Templates bool BagOfItems :: add(Item* value) { if (isFull() || (value == NULL) ) return false; m_container[m_size] = value; m_size++; return true; } // cont ’ d.. template bool Bag :: add(Item * value) { if (isFull( ) || (value == NULL) ) return false; m_container[m_size] = value; m_size++; return true; } // cont ’ d..

18 © Copyright Eliyahu Brutman Templates And STL - 18 Bags With and Without Templates Item * BagOfItems :: getOne( ) { if (isEmpty( )) return NULL; unsigned int index = (unsigned int)( rand( )*m_size/(RAND_MAX+1)); Item* value = m_container[index]; m_container[index] = m_container[m_size-1]; m_size--; return value; } // cont ’ d.. template Item * Bag :: getOne( ) { if (isEmpty( )) return NULL; unsigned int index = (unsigned int)( rand( )*m_size/(RAND_MAX+1)); Item* value = m_container[index]; m_container[index] = m_container[m_size-1]; m_size--; return value; } // cont ’ d..

19 © Copyright Eliyahu Brutman Templates And STL - 19 Bags With and Without Templates bool BagOfItems :: isEmpty( ) const { return (m_size == 0); } bool BagOfItems :: isFull( ) const {return (m_size == m_max_capacity); } // cont ’ d.. template bool Bag :: isEmpty( ) const { return (m_size == 0); } template bool Bag :: isFull( ) const {return (m_size == m_max_capacity); } // cont ’ d..

20 © Copyright Eliyahu Brutman Templates And STL - 20 Bags With and Without Templates unsigned int BagOfItems :: currentSize( ) const { return m_size; } unsigned int BagOfItems :: capacity( ) const {return m_max_capacity; } // end of Bag_Ptr.cpp template unsigned int Bag :: currentSize( ) const { return m_size; } template unsigned int Bag :: capacity( ) const {return m_max_capacity;} // end of Bag.template

21 © Copyright Eliyahu Brutman Templates And STL - 21 Instantiating Bag Objects Bag bag(40); // statically allocated bag for 40 ptrs to int Bag *bagPtr = new Bag (60); // bagPtr holds the // address of a dynamically allocated bag that stores up // to 60 pointers to int Bag > x(25); // statically allocated bag x can hold 25 // pointers to bags, each of which can hold pointers to int Bag > *y = new Bag > (30); // y holds // the address of a dynamically allocated bag that stores // up to 30 pointers to bags of pointers to int

22 © Copyright Eliyahu Brutman Templates And STL - 22 Instantiating Bag Objects When Bag > b = new Bag >(30); is first encountered: First, the class Bag is instantiated Then the class Bag > is instantiated Then the object b is instantiated When Bag and Bag > are encountered subsequently, the classes already exist

23 © Copyright Eliyahu Brutman Templates And STL - 23 Using Bag Objects Suppose a bag has been declared using Bag b(20); Member functions can be invoked on b in the normal fashion Only pointers to int can be stored in b Values returned by b.getOne( ) are always of type int* Outside the class definition, Bag as a type name is changed to Bag Rule holds even in the portion of the.h file where prototypes of non-member functions are declared; each of these prototypes is preceded by the prefix template In Bag.template, constructor and destructor names are still Bag, ~Bag

24 © Copyright Eliyahu Brutman Templates And STL - 24 Operations on OrderedList OrderedListConstruct an empty ordered list of objects isEmptyDetermine whether or not the list is empty getLengthGet the current size of the list removeRemove value at a given position from the list retrieveGet the Item at a particular location in the list insertAdd an object to the list at the appropriate place findReturn the position of a particular object in the list

25 © Copyright Eliyahu Brutman Templates And STL - 25 OrderedList.h #include “List.h” template class OrderedList { public: OrderedList(unsigned int capacity = MAX_LIST); // constructor for // an empty ordered list that can hold up to capacity items; default // size is defined in List.h ~OrderedList( ); // destructor bool isEmpty( ) const; // true if list is empty, false otherwise

26 © Copyright Eliyahu Brutman Templates And STL - 26 OrderedList.h int getLength( ) const; // returns the current size of the list // remove the value at location pos, and return it; precondition: // pos must be a legal list position Item remove (unsigned int pos); // return value at pos without modifying the list; precondition: // pos must be a legal list position Item retrieve (unsigned int pos) const; // cont’d..

27 © Copyright Eliyahu Brutman Templates And STL - 27 OrderedList.h // insert item at appropriate pos’n in list void insert (Item item); // return pos’n of first occurrence of item, or -1 if item isn’t found int find (Item item) const; private: List m_container; // to hold the list of Items }; // end of header file

28 © Copyright Eliyahu Brutman Templates And STL - 28 OrderedList.template #include template OrderedList :: OrderedList (unsigned int capacity ) : m_container(capacity) { } template OrderedList :: ~OrderedList ( ) { } // cont’d..

29 © Copyright Eliyahu Brutman Templates And STL - 29 OrderedList.template template bool OrderedList :: isEmpty( ) const { return m_container.isEmpty( ); } template int OrderedList :: getLength( ) const { return m_container.getLength( ); } // cont’d..

30 © Copyright Eliyahu Brutman Templates And STL - 30 OrderedList.template template Item OrderedList :: remove (unsigned int pos) { return m_container.remove(pos); } template Item OrderedList :: retrieve (unsigned int pos) const { return m_container.retrieve(pos); } // cont’d..

31 © Copyright Eliyahu Brutman Templates And STL - 31 OrderedList.template template void OrderedList :: insert (Item item) { unsigned int k; for ( k = 1; k <= getLength( ); k++ ) if ( item < retrieve(k) ) break; m_container.insert( k, item ); } // cont’d..

32 © Copyright Eliyahu Brutman Templates And STL - 32 OrderedList.template template int OrderedList :: find (Item item) const { unsigned int k; for ( k=1; k <= getLength( ); k++ ) if ( item == retrieve(k) ) return k; return –1; } // end of OrderedList implementation

33 © Copyright Eliyahu Brutman Templates And STL - 33 STL – Why? Reuse. Reusable core components. The programmer can focus on application development, and rely on for portability of components such as: strings, containers, algorithms (sort, search, etc.) and I/O streams. STL had been designed with efficiency in mind Better maintainability

34 © Copyright Eliyahu Brutman Templates And STL - 34 STL Overview For best Generality and Reusability, most of STL ’s components are supplied as templates (functions and classes). Three main component groups: Containers - contain and organize other objects. Iterators - provide a means of sequencing through the elements of a container in some order. Algorithms - perform certain operations on containers ’ elements. Those components are independent of each other, pluggable, and exchangeable, through generic interface

35 © Copyright Eliyahu Brutman Templates And STL - 35 Containers – Overview An STL container is an object that manages a collection of elements. Different containers, with efficiency considerations  For search, operator== is required  For ordering, relational operators are needed, i.e. operator< is required With common, generic interface Also, default constructor, copy constructor, copy assignment operator and destructor are needed. Sequence containers Ordered collection (vector, deque, list) Associative containers Sorted collection (map, multimap, set and multiset) – fast retrieval

36 © Copyright Eliyahu Brutman Templates And STL - 36 Containers Common Functionality Common member functions for all STL containers: empty – returns true if there are no elements in the container, otherwise returns false. size – returns the number of elements currently in the container. max_size – returns the maximum number of elements for a container. erase – erase one or more elements from the container. clear – erase all elements from the container. swap – swaps the elements of two containers.

37 © Copyright Eliyahu Brutman Templates And STL - 37 Iterators The containers provide iterator classes, enabling element iteration and access functionality in a common and general interface

38 © Copyright Eliyahu Brutman Templates And STL - 38 Algorithms Overview – cont’d Algorithms are designed to be a “ plug-in ” to work on any container Search algorithms find, find_if, count, count_if, search, binary_search, etc. Sorting algorithms sort, merge, partition, etc. Other modifying sequence algorithms Relational & minimum / maximum algorithms More …

39 © Copyright Eliyahu Brutman Templates And STL - 39 Interconnectivity of Components The connections between iterators, containers and algorithms: Containers provide iterators as part of their interface. Algorithms are defined in terms of iterators.  There is no direct connection between algorithms and containers. The use of iterators enables writing generic algorithms which are applicable to any container class that provides a standard iterator. Container of T Iterator generates uses Generic Algorithm


Download ppt "© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0."

Similar presentations


Ads by Google