Title: COM262 Object Development
1COM262Object Development
- (1.) Templates
- (2.) Standard Library
- Standard Template Library
2Templates
- enables the specification of an entire range of
related (overloaded) functions or an entire range
of related classes with a single code segment - function templates (generic functions)
- class templates (generic classes)
3Function Templates
- overloaded functions with identical operations
Example Write a program which will identify
the largest value from 3 set of data items
containing 3 values. The 1st set of data items
contain integer values, the 2nd double values
and the 3rd character values.
4Function Templates
- How would you do it ??
- 3 separate functions?
int maxi(int value1 int value2, int value3)
int max value1 if (value2gtmax) max
value2 if (value3gtmax) max value3
return max
5Function Templates
double maxi(double value1 double value2, double
value3) double max value1 if
(value2gtmax) max value2 if (value3gtmax)
max value3 return max
char maxi(char value1 char value2, char value3)
char max value1 if (value2gtmax) max
value2 if (value3gtmax) max value3
return max
6Function Templates
- Can we do it with one function?
- YES
- How ?
- function template!!
7Function Templates - Example
template ltclass Tgt T maxi(T value1, T value2, T
value3) T max value1 if (value2gtmax)
max value2 if (value3gtmax) max value3
return max
8Function Templates -Syntax
- to specify the arguments to the function,
- to specify return type of the function and
- to declare variables within the function
template ltclass Tgt
template ltclass AnyTypegt
template ltclass TypeA, class TypeBgt
9Using Function Templates
// Using template functions include
ltiostream.hgt //template declaration main() int
int13, int24, int35 coutltltMaximum integer
ltltmaxi(int1,int2,int3) double db13.5,
db24.5, db35.5 coutltltMaximum integer
ltltmaxi(db1,db2,db3) char ch1a, ch2b,
ch3c coutltltMaximum integer
ltltmaxi(ch1,ch2,ch3)
template ltclass Tgt T maxi(T value1, T value2, T
value3) T max value1 if (value2gtmax)
max value2 if (value3gtmax) max value3
return max
10Function Template - another example
Write a function template which can be used to
print out a list of items. The function
formal parameter list consists of 2 arguments
the first a pointer to an array and the second a
count of the number of items in the list. The
function does not return any values
- How would you define a function template for the
above???
11Function Template - another example
- // template header
- template lt class Tgt
- //function declaration
- void printarray(T array, const int count)
- // function body
- for (int i 0 ilt count i)
- coutltltarrayiltlt
- cout ltlt endl
12Using Function Templates
// Using template functions include
ltiostream.hgt //template declaration main() int
acnt5, ccnt6 int a 1,2,3,4,5 char c
hello coutltlt1st list contains
printarray(a, acnt) coutltlt\n2nd list
contain printarray(c,ccnt)
// template header template lt class Tgt //function
declaration void printarray(T array, const int
count) // function body for (int i 0 ilt
count i) coutltltarrayiltlt
cout ltlt endl
13Overloading Function Templates
- Function overloading and function templates are
closely related - function templates can also be overloaded
- function templates with same name but different
function parameters - function template with same name as non-template
functions
14Overloading Resolution by Compiler
- Tries to find a precise match name and argument
types (non-template functions take precedence
over potential generated template functions) - Next - use function template to generate template
function with a precise match - Oops.. error
15Class Templates
- parameterised types
- looks like a conventional class definition except
for the template header preceding the definition - templateltclass Tgt
16Class Templates
Example Defining a class template Store which
holds a data value that must be initialised
before it is retrieved
17Class Templates
Defining a class template
template ltclass Tgt class Store private T
item boolean havevalue public Store(void)
// default constructor T
getItem(void) void setItem(const T
x)
18Class Templates
Defining a class template methods
(function template)
templateltclass Tgt T StoreltTgt getItem(void)
if (!havevalue) cerrltltNo data
present!ltltendl exit(1)
return item
19Class Templates
Defining a class template methods
(function template)
templateltclass Tgt void StoreltTgt setItem(const T
x) havevalue true itemx
templateltclass Tgt StoreltTgtStore(void)
havevalue (false)
20Class Templates
Declaring template class objects
// declaring an object for storing int
type Storeltintgt data // declaring an array for
storing 10 char type Storeltchargt ch_list10
21Class Templates
Using the class template
include ltiostream.hgt include store.h void
main(void) Storeltintgt number Storeltchargt
letter Storeltfloatgt realno number.
setItem(3) letter. setItem(z)
coutltltletter. getItem() coutltltendl coutltltnumber.
getItem() coutltltendl coutltltrealno. getItem()
Output???
22Class Templates
Output
z 3 No data present!
23Abstract Data Types
(Later in module..)
5
4
3
2
1
0
An array is a simple LIST STACK last in first
out (LIFO) QUEUE first in first out
(FIFO) DEQUE double-ended queue..
24class Deque int seq //pointer to array
int size // max no. of items int left //
leftmost index int right // rightmost index
void underflow( ) // error msg void
overflow( ) // error msg public Deque(int
sz 10) //default values Deque( ) delete
seq void insert_left(int item) void
insert_right(int item) int remove_left( )
int remove_right()
Deque
Queue
Stack
25template ltclass ListType gt class Deque
ListType seq //pointer to array int size
// max no. of items int left // leftmost
index int right // rightmost index void
underflow( ) // error msg void overflow( )
// error msg public Deque(int sz 10)
//default values Deque( ) delete seq
void insert_left(ListType item) void
insert_right(ListType item) ListType
remove_left( ) ListType remove_right()
26Deque
template ltclass ListTypegt class Queue private
Dequelt ListType gt public Queue(int sz
10) void insert(ListType item) ListType
remove( )
template ltclass ListType gt class Stack private
Dequelt ListType gt public Stack(int sz
10) void insert(ListType item) ListType
remove( )
27Templates Points to Note
- compiler generates codes from the templates
- excessive use of templates can increase the size
of the source code substantially - arbitrary number of template parameters
- type parameters (preceded with keyword class)
- value parameters (like ordinary function
parameters but CANNOT be of floating point type)
28Templates
Summary
- Templates
- function templates (generic functions)
- class templates (generic classes)
- relationship between function templates and
function overloading - explicitly overloading function templates
- templates enhance programmer efficiency
- excessive use of templates can increase sources
code size excessively.
29Standard Library Standard Template Library (STL)
30- Standard Library
- e.g. fstream, iostream
- C standard library is heterogenous
- Contains software from very different sources
that have different styles of design and
implementation - e.g. error and exception handling
- parts of the library, such as string classes,
support detailed error handling - check for every possible problem that might
occur and throw an exception if there is an
error - other parts, e.g. STL and valarrays, prefer
speed over safety - rarely check for logical errors and throw
exceptions only if runtime errors occur
31- C Standard Template Library (STL)
- Dont have to re-invent the wheel
- Need to know about classes, constructors etc.
- Motivation? Many felt C classes were
inadequate in situations requiring containers for
user defined types, and methods for common
operations on them - e.g. might need self-expanding arrays, which can
easily be searched, sorted, added to or removed
from without messing about with memory
reallocation and management - Other Object-Oriented languages used templates
to implement this sort of thing, and hence they
were incorporated into C
32STL Components Containers Sequence Associative
Container Adapters Iterators Algorithms Ranges
Iterator adapters insert iterators stream
iterators reverse iterators Manipulating
algorithms
33STL Containers Vectors Deques Lists Sets
Multisets Maps Multimaps
34include ltstringgt // for STL string using
stdstring include ltiostream.hgt include
ltconio.hgt int main() string
people_I_like3 // define string array
people_I_like0 "neitzche" // fill up string
array people_I_like1 " steiner "
people_I_like2 " goethe "
for( int i0 i lt 3 i ) cout
ltlt people_I_likei ltlt endl
getch() return 0 What if I want to add
another person to my list???
35include ltstringgt // for STL string using
stdstring include ltiostream.hgt include
ltconio.hgt include ltvectorgt // for STL
vector int main() stdvectorltstringgt
people_I_like // define string
vector people_I_like.push_back("neitzche") //
fill up string vector people_I_like.push_
back("steiner") people_I_like.push_back(
"goethe") people_I_like.push_back("wagne
r") for( int i0 i lt
people_I_like.size() i ) cout
ltlt people_I_likei ltlt endl
people_I_like.clear() getch()
return 0
36include ltstringgt // for STL string using
stdstring include ltiostream.hgt include
ltconio.hgt include ltlistgt // for STL list int
main() stdlistltstringgt
people_I_like // define string
list people_I_like.push_back("neitzche") //
fill up string list people_I_like.push_ba
ck("steiner") people_I_like.push_back("g
oethe") people_I_like.push_back("wagner"
) for( int i0 i lt people_I_like.size(
) i ) cout ltlt
people_I_likei ltlt endl
people_I_like.clear() getch()
return 0
37Sequence containers
Time overhead of operations
38STL Iterators Iterator categories Input,
Output, Forward, Bidirectional, Random
Access Auxiliary Interator Functions advance(),
distance(), iter_swap() Interator
Adapters Reverse, Insert, Stream
39The Iterator Hierarchy
40- There are 60 different algorithms
- in 8 main categories in the STL..
- Nonmodifying Sequence Operations - these extract
information, find, position within or move
through elements but don't change them, e.g.
find() . - Modifying Sequence Operations - these are
miscellaneous functions that do change the
element they act on, e.g. swap(), transform(),
fill(), for_each() . - Sorted Sequences - sorting and bound checking
functions, e.g. sort(), lower_bound() . - Set Algorithms - create sorted unions,
intersections and so on, e.g. set_union(),
set_intersection() . - Heap Operations - e.g. make_heap(), push_heap(),
sort_heap() . - Minimum and Maximum - e.g. min(), max(),
min_element(), max_element() . - Permutations - e.g. next_permutation(),
prev_permutation() . - Numeric - include ltnumericgt for general numerical
algorithms, e.g. partial_sum() .
41Algorithms include ltalgorithmgt
42STL Algorithms Non-modifying Algorithms Counting
elements, Minimum Maximum, Searching
Elements, Comparing Ranges Modifying
Algorithms Copying Elements, Transforming
Combining Elements, Swapping Elements, Assigning
New Values, Replacing Elements Removing
Algorithms Removing certain values, Removing
duplicates
43Removing Algorithms Removing certain values,
Removing duplicates Mutating Algorithms Reversin
g the order of elements, Rotating elements,
Permuting elements, Shuffling elements, Moving
elements to the front Sorting
Algorithms Sorting all elements, Partial
sorting, Sorting according to the nth element,
Heap algorithms Sorted Range Algorithms Searchin
g elements, Merging elements Numeric
Algorithms Processing results, Converting
relative and absolute values
44Special Containers Stacks Queues Priority
Queues Bitsets Numerics Input/Output using
Stream Classes Internationalisation Allocators Str
ings
45Some String Access Functions include ltstringgt
find(...) Find substring or character, start at
start find_first_of(...) Find first occurrence
of any characters in given set, starting from
start of string find_last_of(...) Find last
occurrence of any characters in given set,
starting from start of string find_not_first_of(.
..) Find first occurrence of characters _not_ in
given set, starting from start of string
find_last_not_of(...) Find last occurrence of
characters _not_ in given set, starting from
start of string rfind(...) Find substring or
character, start at end size() Number of
elements in vector Random access to return a
single character - no bounds checking at(...)
Random access to return a single character - with
bounds checking Concatenate strings swap( , )
Swap two strings insert( , ) Insert a string at
the specified position replace(...) Replace
selected substring with another string
46(odd) stuff.. Function objects xxxx auto_ptr x
xxx using namespace std xxxx explicit