39
EE4E. C++ Programming Lecture 5 Lecture 5 Templates and the Standard Templates and the Standard Template Library (STL) Template Library (STL)

EE4E. C++ Programming

  • Upload
    pello

  • View
    53

  • Download
    2

Embed Size (px)

DESCRIPTION

EE4E. C++ Programming. Lecture 5 Templates and the Standard Template Library (STL). Contents. Introduction Function templates Class templates Creating function templates from class templates The Standard Template Library (STL). Introduction. Templates are a powerful feature of C++ - PowerPoint PPT Presentation

Citation preview

Page 1: EE4E. C++ Programming

EE4E. C++ Programming

Lecture 5Lecture 5

Templates and the Standard Template Templates and the Standard Template Library (STL)Library (STL)

Page 2: EE4E. C++ Programming

Contents

IntroductionIntroduction Function templatesFunction templates Class templatesClass templates Creating function templates from class Creating function templates from class

templatestemplates The Standard Template Library (STL)The Standard Template Library (STL)

Page 3: EE4E. C++ Programming

Introduction Templates are a powerful feature of C++ Templates are a powerful feature of C++

They allow the programmer to specify with a single code They allow the programmer to specify with a single code segment an entire range of related functions or classessegment an entire range of related functions or classes

For example we might write a For example we might write a sort()sort() function template able function template able to sort to sort intsints, , floatsfloats, , charschars and programmer defined classes and programmer defined classes

We might write a We might write a linked listlinked list class template able to handle class template able to handle many different data typesmany different data types

The The Standard Template LibraryStandard Template Library is a sophisticated set of class is a sophisticated set of class templates enabling us to use generalized container classes templates enabling us to use generalized container classes

Page 4: EE4E. C++ Programming

Function templates Function templates are useful if we want to Function templates are useful if we want to

perform identical operations on different types of perform identical operations on different types of datadata Examples would include searching and sorting Examples would include searching and sorting

arrays of different data typesarrays of different data types The algorithms used would be the same for all The algorithms used would be the same for all

data typesdata types Only object equality and relational tests would Only object equality and relational tests would

differdiffer

Page 5: EE4E. C++ Programming

Function template definitions begin with the Function template definitions begin with the templatetemplate keywordkeyword

A list of formal type parameters follows in angle (< A list of formal type parameters follows in angle (< and >) bracketsand >) brackets

template <class T>template <class T> function_namefunction_name

template <class A, class B> function_nametemplate <class A, class B> function_name

The function template is The function template is instantiated instantiated by specifying by specifying actual types (which can be primitive types or user actual types (which can be primitive types or user defined types) in place of the formal typesdefined types) in place of the formal types

Page 6: EE4E. C++ Programming

Example

A function template A function template printArray()printArray() that prints that prints the contents of an array of any instantiated the contents of an array of any instantiated typetype

template class<T> void printArray(const T* array, template class<T> void printArray(const T* array, const int count)const int count){{

for (int i=0; i<count; i++)for (int i=0; i<count; i++){{

cout << array[i] << “ “;cout << array[i] << “ “;cout << “\n”;cout << “\n”;

}}}}

Page 7: EE4E. C++ Programming

void main()void main(){{

const int n=5;const int n=5;

int intArray[n]={1,2,3,4,5};int intArray[n]={1,2,3,4,5};float floatArray[n]={1.0,2.0,3.0,4.0,5.0};float floatArray[n]={1.0,2.0,3.0,4.0,5.0};char charArray[n]=“Hiya”;char charArray[n]=“Hiya”;

printArray(intArray,n);printArray(intArray,n);printArray(floatArray,n);printArray(floatArray,n);printArray(charArray,n);printArray(charArray,n);

}}

Page 8: EE4E. C++ Programming

The The compilercompiler in this case instantiates the in this case instantiates the following following printArray()printArray() functions functions

printArray(const int*, const int)printArray(const int*, const int)

printArray(const float*, const int)printArray(const float*, const int)

printArray(const char*, const int)printArray(const char*, const int)

No runtime overhead is involvedNo runtime overhead is involved

If If TT is replaced by a programmer defined type is replaced by a programmer defined type (such as (such as DateDate), then the complier will look for a ), then the complier will look for a overloaded overloaded operator<<() operator<<() functionfunction

Page 9: EE4E. C++ Programming

void main()void main(){{

const int n=5;const int n=5;Date d(1,1,1990);Date d(1,1,1990);

Date* DateArray=new Date[n];Date* DateArray=new Date[n];for (int i=0; i<n; i++)for (int i=0; i<n; i++)

DateArray[i]=d++;DateArray[i]=d++;

// // operator<<(ostream& os, const Date& d) operator<<(ostream& os, const Date& d) called herecalled hereprintArray(DateArray,n);printArray(DateArray,n);

}}

Page 10: EE4E. C++ Programming

Class templates Class templates enable reusable data types to be Class templates enable reusable data types to be

easily createdeasily created Often called Often called generic programminggeneric programming

For example we can create a generic stack (a last For example we can create a generic stack (a last in first out data structure) using class templatesin first out data structure) using class templates The generic stack can be instantiated with any The generic stack can be instantiated with any

data typedata type Stack of integers, stack of doubles, stack of Stack of integers, stack of doubles, stack of

dates etcdates etc

Page 11: EE4E. C++ Programming

// Stack class template// Stack class templatetemplate <class T> class Stacktemplate <class T> class Stack{{

private:private:int size;int size; // No. of elements in the stack// No. of elements in the stackint top;int top; // Location of the top element// Location of the top elementT* stackPtr;T* stackPtr; // Pointer to the stack// Pointer to the stack

public:public:Stack(int);Stack(int);~Stack() { delete[] stackPtr; }~Stack() { delete[] stackPtr; }int push(const T&);int push(const T&); // Push an element// Push an elementint pop(T&);int pop(T&); // Pop an element// Pop an elementint isEmpty() { return top==-1;}int isEmpty() { return top==-1;}int isFull() { return top==size-1;}int isFull() { return top==size-1;}

};};

Page 12: EE4E. C++ Programming

template<class T> Stack<T>::Stack(int a)template<class T> Stack<T>::Stack(int a){{

size=a;size=a;top=-1;top=-1; // Initially empty// Initially emptystackPtr=new T[size];stackPtr=new T[size]; // Allocate memory// Allocate memory

}}

template<class T> int Stack<T>::push(T& val)template<class T> int Stack<T>::push(T& val){{

if (!isFull()) { stackPtr[++top]=val;if (!isFull()) { stackPtr[++top]=val;return 1; return 1;

}}return 0;return 0;

}}

template<class T> int Stack<T>::pop(T& val)template<class T> int Stack<T>::pop(T& val){{

if (!isEmpty()) { val=stackPtr[top--];if (!isEmpty()) { val=stackPtr[top--];return 1;return 1;

}}return 0;return 0;

}}

Page 13: EE4E. C++ Programming

void main()void main(){{

Stack<char> charStack(7);Stack<char> charStack(7);char[] name=“Michael”;char[] name=“Michael”;

int j=0;int j=0;while(charStack.push(name[j])while(charStack.push(name[j])

j++;j++;

char c;char c;cout << “My name in reverse is : “;cout << “My name in reverse is : “;while(charStack.pop(c))while(charStack.pop(c))

cout << c;cout << c;

}}

Page 14: EE4E. C++ Programming

This code assumes that an overloaded This code assumes that an overloaded assignment operator function exist for assignment operator function exist for programmer defined data typesprogrammer defined data types This This mustmust be provided if the object used be provided if the object used

with the with the StackStack class contains class contains dynamically allocated memorydynamically allocated memory

Page 15: EE4E. C++ Programming

Creating function templates from class templates We can easily create a We can easily create a functionfunction template by template by

passing a passing a class template class template as an argument to a as an argument to a functionfunction A classic example is a A classic example is a sort()sort() function function

template which sorts the contents of a template which sorts the contents of a container template (for example and container template (for example and array) passed as an argumentarray) passed as an argument

Page 16: EE4E. C++ Programming

We can demonstrate this by first creating a We can demonstrate this by first creating a simple simple VectorVector template (like an array) template (like an array)

template <class T> class Vectortemplate <class T> class Vector{{

private:private:T* v;T* v;int size;int size;

  public:public:

Vector(int) ;Vector(int) ; // Constructor// Constructorint getSize( ) { return size; }int getSize( ) { return size; }T& operator[] (int ); T& operator[] (int ); // overloaded []// overloaded []

};};

Page 17: EE4E. C++ Programming

We can then create a We can then create a sort()sort() function function templatetemplate

template<class T> void sort(Vector<T>& v)template<class T> void sort(Vector<T>& v){{

// sort the elements of v into increasing// sort the elements of v into increasing// order using a bubble sort// order using a bubble sort

  int size=v.getSize();int size=v.getSize();for (int i=0; i<size-1; i++)for (int i=0; i<size-1; i++)

for (int j=size; i<j; j--)for (int j=size; i<j; j--)if (v[j]<v[j-1])if (v[j]<v[j-1]) // swap v[j] & v[i] // swap v[j] & v[i]{{

T t = v[j];T t = v[j];v[j]=v[j-1];v[j]=v[j-1];v[j-1] = t;v[j-1] = t;

}}}}

Page 18: EE4E. C++ Programming

void main()void main(){{

Vector<int>& vi(100);Vector<int>& vi(100);Vector<char*>& vc(100);Vector<char*>& vc(100);Vector<float>& vf(100);Vector<float>& vf(100);Vector<Circle>& vci(100);Vector<Circle>& vci(100);

// initialize the vectors// initialize the vectors// …..// …..

..sort(vi);sort(vi);sort(vc);sort(vc);sort(vf);sort(vf);sort(vci);sort(vci);

}}

Page 19: EE4E. C++ Programming

The compiler will try and create the correct The compiler will try and create the correct sort()sort() functions by instantiating the templated functionsfunctions by instantiating the templated functions

It will run into 2 problems in this exampleIt will run into 2 problems in this example Instantiating Instantiating sort()sort() with a char* (a string) with a char* (a string)

argument will produce incorrect resultsargument will produce incorrect resultsThe ‘<‘ operator will not test for alphabetical The ‘<‘ operator will not test for alphabetical

ordering of the stringsordering of the strings Instantiating Instantiating sort()sort() with a with a CircleCircle object object

argument will produce a compilation errorargument will produce a compilation errorWe need an overloaded We need an overloaded operator<()operator<() function function

defined on defined on CircleCircle objects objects

Page 20: EE4E. C++ Programming

We can create We can create sort()sort() functions for specific functions for specific datatypes that will override the instantiated datatypes that will override the instantiated functionfunction

template<class T> void sort(Vector<char*>& v)template<class T> void sort(Vector<char*>& v){{

// sort the elements of v into increasing// sort the elements of v into increasing// order using a bubble sort// order using a bubble sortint size=v.getSize();int size=v.getSize();for (int i=0; i<size()-1; i++)for (int i=0; i<size()-1; i++)

for (int j=size()-1; i<j; j--)for (int j=size()-1; i<j; j--)if (strcmp(v[j],v[j-1])<0)if (strcmp(v[j],v[j-1])<0){{

T t = v[j];T t = v[j];v[j]=v[j-1];v[j]=v[j-1];v[j-1] = t;v[j-1] = t;

}}}}

Page 21: EE4E. C++ Programming

We can also create an We can also create an operator<()operator<() function function for for Circle Circle objectsobjects

int operator < (Circle& c1,Circel& c2)int operator < (Circle& c1,Circel& c2){{return c1.radius<c2.radius;return c1.radius<c2.radius;}}

Page 22: EE4E. C++ Programming

Other features of templates

Templates and friendsTemplates and friends With templates, friendship can be With templates, friendship can be

established between either a class established between either a class template or a particular instantiation of template or a particular instantiation of the template and global/member the template and global/member functions or entire classesfunctions or entire classes

A few examples will clarify this:A few examples will clarify this:

Page 23: EE4E. C++ Programming

Declare a function f() to be a friend of every class specialization of class template XDeclare a function f() to be a friend of every class specialization of class template X

Declare every member function of class Y to be a friend of every class specialization of class template XDeclare every member function of class Y to be a friend of every class specialization of class template X

template<class T> class Xtemplate<class T> class X{{

……..friend void f();friend void f();……..

}}

template<class T> class Xtemplate<class T> class X{{

……..friend class Y;friend class Y;……..

}}

Page 24: EE4E. C++ Programming

Declare a function f(X<T>) to be a friend of class specialization X<T> for any T (such as float)Declare a function f(X<T>) to be a friend of class specialization X<T> for any T (such as float)

Declare every member function of class specialization Y<T> to be a friend of class specialization X<T> for any T (such as float)Declare every member function of class specialization Y<T> to be a friend of class specialization X<T> for any T (such as float)

template<class T> class Xtemplate<class T> class X{{

……..friend void f(X<T> &);friend void f(X<T> &);……..

}}

template<class T> class Xtemplate<class T> class X{{

……..friend class Y<T>;friend class Y<T>;……..

}}

Page 25: EE4E. C++ Programming

The Standard Template Library (STL)

The The Standard Template LibraryStandard Template Library (STL) is an addition to (STL) is an addition to the C++ Standard Library the C++ Standard Library Developed at the Hewlett-Packard Labs in the mid-late Developed at the Hewlett-Packard Labs in the mid-late

90’s90’s STL defines powerful, template-based, reuseable STL defines powerful, template-based, reuseable

components that implement many common data components that implement many common data structures and algorithms to process those data structures and algorithms to process those data structuresstructures

STL is extremely complex, being optimised for STL is extremely complex, being optimised for efficiency. We will only scratch the surfaceefficiency. We will only scratch the surface

Page 26: EE4E. C++ Programming

STL is based on 3 componentsSTL is based on 3 components ContainersContainers IteratorsIterators AlgorithmsAlgorithms

Template-based containers are data structures used Template-based containers are data structures used to group objects of any typeto group objects of any type Examples include linked lists, vectors and setsExamples include linked lists, vectors and sets

Iterators encapsulate the mechanisms used to Iterators encapsulate the mechanisms used to access container elementsaccess container elements A simple pointer can be used as an iterator for a A simple pointer can be used as an iterator for a

standard arraystandard array

Page 27: EE4E. C++ Programming

Algorithms are functions that perform common Algorithms are functions that perform common manipulations on containersmanipulations on containers Examples include searching and sorting algorithmsExamples include searching and sorting algorithms There are around 70 algorithms implemented in the There are around 70 algorithms implemented in the

STLSTL A key aspect of the STL is that an algorithm can be A key aspect of the STL is that an algorithm can be

applied to a container without regard to the exact applied to a container without regard to the exact implementation of the containerimplementation of the container The container’s iterator just has to support the The container’s iterator just has to support the

minimum requirement of the algorithmminimum requirement of the algorithm This means that programmers can write one This means that programmers can write one

algorithm which can be applied to multiple algorithm which can be applied to multiple containerscontainers

Page 28: EE4E. C++ Programming

Containers Containers divided into 3 main categoriesContainers divided into 3 main categories

Sequence containersSequence containersEssentially linear data structuresEssentially linear data structures

Associative containersAssociative containersCan be searched quickly using Can be searched quickly using

name/value pairingsname/value pairings Container adaptersContainer adapters

Stacks, queues and priority queuesStacks, queues and priority queues

Page 29: EE4E. C++ Programming

Examples of sequence STL containers includeExamples of sequence STL containers include vectorvector

Provides random access with constant time Provides random access with constant time insertions and deletions at the endinsertions and deletions at the end

dequedeque (double entry queue) (double entry queue)Provides random access with constant time Provides random access with constant time

insertions and deletions at the beginning insertions and deletions at the beginning and the endand the end

listlistProvides linear time access but constant Provides linear time access but constant

time insertions and deletions at time insertions and deletions at anyany position position in the listin the list

Page 30: EE4E. C++ Programming

Examples of associative STL containers Examples of associative STL containers includeinclude setset

Provides rapid lookup (set Provides rapid lookup (set membership), no duplicates aroundmembership), no duplicates around

multisetmultisetAsAs above but allows duplicatesabove but allows duplicates

Page 31: EE4E. C++ Programming

Iterators

Iterators allow generic algorithms to ‘plug Iterators allow generic algorithms to ‘plug in’ to different containersin’ to different containers As long as the container supports the As long as the container supports the

iterator that the algorithm uses to access iterator that the algorithm uses to access container elements, the algorithm can be container elements, the algorithm can be applied to it applied to it

Page 32: EE4E. C++ Programming

vector

list

Container Iterator Algorithm

sort

find

Page 33: EE4E. C++ Programming

There are different classes of iterator to support There are different classes of iterator to support things like linear or random accessthings like linear or random access

However, certain iterator operations are uniform However, certain iterator operations are uniform and can be applied to all containersand can be applied to all containers * (de-referencing) allows access to the element * (de-referencing) allows access to the element

to pointer to by the iteratorto pointer to by the iterator ++ (increment) moves the iterator to the next ++ (increment) moves the iterator to the next

elementelement begin()begin() points the iterator at the first element points the iterator at the first element end()end() points the iterator at the last element points the iterator at the last element

Page 34: EE4E. C++ Programming

Generally speaking, we have the following sub-Generally speaking, we have the following sub-division of iterators and associated containers division of iterators and associated containers Sequence containers Sequence containers vector, dequevector, deque

Random access iteratorsRandom access iterators Sequence container Sequence container listlist

Linear bidirectional iteratorLinear bidirectional iterator Associative containers Associative containers set, multi-set, map, set, multi-set, map,

multi-mapmulti-mapLinear bidirectional iteratorLinear bidirectional iterator

No iterators supported for No iterators supported for stack, queue, priority stack, queue, priority queuequeue

Page 35: EE4E. C++ Programming

Iterator operations

Depends on iterator typeDepends on iterator type A few examplesA few examples

++p, p++,--p, p--(pre and post ++p, p++,--p, p--(pre and post increment/decrement)increment/decrement)

Applies to bidirectional and random accessApplies to bidirectional and random access *p (de-referencing)*p (de-referencing)

Applies to bidirectional and random accessApplies to bidirectional and random access p==p1(test for equality)p==p1(test for equality)

Applies to bidirectional and random accessApplies to bidirectional and random access

Page 36: EE4E. C++ Programming

p+=i, p-=i (increment/decrement iterator p+=i, p-=i (increment/decrement iterator p by i positions)p by i positions)Applies to random access onlyApplies to random access only

p[i] (returns a reference to the element p[i] (returns a reference to the element offset from p by i positions)offset from p by i positions)Applies to random access onlyApplies to random access only

p<=p1(returns true if iterator p less than p<=p1(returns true if iterator p less than iterator p1 (ie it is before p1 in the iterator p1 (ie it is before p1 in the container)container)Applies to random access onlyApplies to random access only

Page 37: EE4E. C++ Programming

Example. vector

Enables efficient random access rather like an Enables efficient random access rather like an array but can re-size itselfarray but can re-size itself

Supports a random access iteratorSupports a random access iterator All STL algorithms can operate on a All STL algorithms can operate on a vectorvector as as

they all support random accessthey all support random access A A vector vector has a has a sizesize (the actual number of elements (the actual number of elements

in the container) and a in the container) and a capacitycapacity (the number of (the number of elements that can be added before the elements that can be added before the vectorvector resizes)resizes)

Page 38: EE4E. C++ Programming

#include <vector>#include <vector>

int main()int main(){{

int array[6]={1,2,3,4,5,6};int array[6]={1,2,3,4,5,6};

vector<int> vec(array,array+6);vector<int> vec(array,array+6);

for (int *ptr=array; ptr!=(array+6); ptr++)for (int *ptr=array; ptr!=(array+6); ptr++)cout<<*ptr;cout<<*ptr;

vector<T>::iterator it;vector<T>::iterator it;for (it=vec.begin(); it!=vec.end(); it++)for (it=vec.begin(); it!=vec.end(); it++)

cout << *it;cout << *it;

// sort the vector// sort the vectorsort(vec.begin(),vec.end());sort(vec.begin(),vec.end());

}}

Page 39: EE4E. C++ Programming

The previous program shows the similarity The previous program shows the similarity between array access using pointers and between array access using pointers and container access using an iterator container access using an iterator Also de-referening an iterator (pointer) to Also de-referening an iterator (pointer) to

access the container (array) elementaccess the container (array) element Also the program shows how a Also the program shows how a sort()sort()

function is calledfunction is called Iterators passed as argumentsIterators passed as arguments

In general the In general the STLSTL is enormously powerful is enormously powerful and should always be used in preference to and should always be used in preference to custom written container classescustom written container classes