Title: Templates and the STL
1Templates and the STL
2Template (generic) classes
- the behavior of a container class does not depend
of the kind of elements stored in the container - how can we create a generic (type independent)
collection class using C? - drawbacks of typedef
- have to change source code (recompile) for each
type - cant have multiple containers whose elements are
of different types - an alternative define a class template
- template for creating a class
3Function templates
- template - a pattern or a mold
- functions/methods have data parameters
- void f (int p1, float p2, Customer p3)
- argument provided when function is called
- function templates also have type parameters
- from one function template multiple actual
functions can be generated (by the compiler) - allow a programmer to write "generic" functions -
type independent
4overloaded Swap
void Swap(int first, int second) int
temp first first second second
temp
differ only in the type!
void Swap(string first, string second)
string temp first first second
second temp
5generic Swap
1. Swap is a function template 2. Item is a type
parameter 3. keyword typename and class are
interchangeable 4. template function prototype
and definition must be in the same file 5.
actual type substituted for Item must be
"assignable"
6Function instantiation
- no object code is created from a function
template - compiler generates object code for an actual
function from a function template when needed - when compiling a call to the function
- substitutes argument type for the type parameter
- each call with a different argument type results
in object code for a new actual function
7Class templates
- make it possible to have several objects of a
container class, each of which holds a different
type of element - Stack of ints Stack of strings Stack of ?
- declaration and implementation of a template
class have to be compiled together - template class implementation requires "messy"
syntax
8Class template for Stack
template lt typename SE gt class Stack
public - - - Stack ( ) void
push (const SE newElement) - - -
SE top ( ) const private SE
myArraySTACK_CAPACITY int myTop
Class name is StackltSEgt
9declaring StackltSEgt objects
int main ( ) Stack ltintgt samples Stack
ltfloatgt cost Stack ltstringgt names Stack
ltcustomergt line - - -
10implementing a template class
- cumbersome syntax needed
- each method is a template so is preceded by the
template directive - class name is StackltSEgt
template lttypename SEgt StackltSEgtStack( )
- - - -
11Compiling template classes
- compiler cannot separately compile a template
class - compiler needs to know the actual type to
substitute - compiler generates code when a template class
object is declared - substitutes actual type for the type parameter
- needs access to the class implementation, not
just the class declaration - compiler generates separate code for each actual
type substituted for the type parameter
12Two solutions
Client.cpp Client.cpp
include stack
include stack.h
client program
client program
stack.h
stack
Stack template class declaration
Stack template class declaration followed by
implementation
include stack.cpp
stack.cpp
implementation
13Standard Template Library (STL)
- is a library of generic container classes which
are both efficient and functional - C STL developed in early 90's at Hewlett
Packard Laboratories - Alex Stepanov and Meng Lee
- became part of C standard in 1994
- implementations available by late 90's
- see web page for STL Programmer's Guide
14STL and Reuseability
- STL is part of a movement toward libraries of
reusable code - function libraries (reusable algorithms)
- class libraries (reusable ADTs)
- Java 1.2 introduced a library of Collection
classes - http//java.sun.com/docs/books/tutorial/index.htm
l - data and algorithms packaged together (O-O)
- STL separates data and algorithms
- iterators allow algorithms to operate on data
15STL components
- Containers
- templates for classes which hold a collection of
elements - Algorithms
- templates for functions which operate on a range
of elements from a container - range is specified by iterators
- Iterators
- give access to the elements in a container
- allow for movement from one element to another
16STL container classes
- Sequences - elements arranged in a linear order
- vectorltTgt - fast inserts only at the end random
access - listltTgt - fast inserts anywhere no random access
- dequeltTgt - fast inserts at the beginning and the
end - Adapters - provides a new interface (set of
operations) for one of the sequences - stackltTgt ex stackltintgt operands
- queueltTgt ex queueltCustomergt line
- priority_queueltTgt
- Associative Containers - elements have key values
- set, map, multiset, multimap
17vectorltTgt
- growable, self-contained, type-independent array
- element type specified when a vector is declared
- vectorltdoublegt numbers
- vectorltcashiergt checkOutStations
- has a set of operations (methods)
- capacity increases when needed
- some vectors
- vectorltintgt v1 (capacity is 0)
- vectorltfloatgt v2 (10) (capacity is 10 size
is 10) - vectorltstringgt v3 (5, "C") (capacity is 5
size is 5)
18Some vectorltTgt methods
- V.capacity( ) //size of array currently
allocated - V.size( ) //number of values V contains
- V.empty( ) //true iff V.size( ) is 0
- V.reserve(n) //grow V so its capacity is n
- V.push_back(val) //add val at end of V
- V.pop_back( ) //erase V's last element
- Vi //access element of V whose
index is i - V.at(i) //access element of V whose
index is i
19include ltiostreamgt include ltvectorgt using
namespace std bool Search(const vectorltintgt V,
int item) int main ( ) vectorltintgt
numbers int number while (cin gtgt
number) // enter ltcontrolgt D to stop the
loop if (Search(numbers, number))
cout ltlt "Duplicate" ltlt endl
else numbers.push_back(number) cout
ltlt "number of unique values " ltlt numbers.size(
) return 0 bool Search(const vectorltintgt V,
int item) int p 0 while(p lt
V.size( ) ) if (item Vp) // or
V.at(p) return true
else p return false
20STL iterators
- iterators are "pointer-like" objects
- provide a generic way to access the elements of
any container class - many STL algorithms require iterators as
arguments - some STL algorithms return an iterator
- each STL container class has an iterator class
associated with it - vectorltTgtiterator
- listltTgtiterator
- stackltTgt and queueltTgt don't have iterators
- why?
21Iterator categories
- category determines available operations
- forward iterator
- iter (increment)
- iter (dereference)
- and ! (equality comparison)
- bidirectional iterator adds
- iter-- (decrement)
- random-access iterator adds
- itern (constant time access to
arbitrary element) - iter n (increment n times)
22STL Algorithms
- are function templates designed to operate on a
sequence of elements rather than methods - the sequence is designated by two iterators
- most container classes have the following two
methods - begin( ) - returns an iterator positioned
at the container's
first element - end( ) - returns an iterator
positioned past the
container's last element (past-the-end) - C.begin( ), C.end( ) specifies a sequence which
contains all elements of the container C
23STL Algorithms
- some examples of STL algorithms
- find (iter1, iter2, value) //returns an
iterator - max_element (iter1, iter2) //returns an iterator
- sort (iter1, iter2) //sorts
using lt - for_each (iter1, iter2, F) //applies F to
every
//item - see STL Programmer's Guide link on home page
24include ltiostreamgt include ltvectorgt include
ltalgorithmgt using namespace std int main ( )
vectorltintgt numbers int number
while (cin gtgt number) if
(find (numbers.begin ( ), numbers.end ( ),
number) ! numbers.end ( ))
cout ltlt "Duplicate" ltlt endl
else numbers.push_back(number) cout
ltlt "number of unique values " ltlt numbers.size(
) return 0
25include ltiostreamgt include ltvectorgt include
ltalgorithmgt include ltcstdlibgt using namespace
std void set (int val) void display (int
val) int main( ) vectorltintgt A(5)
for_each (A.begin ( ), A.end ( ), set) // would
not work if vectorltintgt A used for_each
(A.begin ( ), A.end ( ), display) cout ltlt
endl sort (A.begin ( ), A.end ( )) //
operatorlt must be defined for A's element type
for_each (A.begin ( ), A.end ( ), display)
cout ltlt endl return 0 void set (int val)
val rand ( ) void display (int val)
cout ltlt " " ltlt val
26listltTgt class
- another STL container class
- used for storing a linear collection of like
items - comparison to a vector?
- linked list vs array is the underlying data
structure - no indexing (iterators are bidirectional)
- inserts and deletes anywhere are done in a
constant amount of time
27a listltTgt data structure
head size
------
2
28Basic list class methods
- list( ) // construct an
empty list - list (const listltTgt aList) // copy constructor
- list( ) //
destructor - listltTgt operator (const listltTgt aList)
// assignment operator - bool empty( )
- int size( )
29Some more list methods
- L.push_back(value) // append value to L
- L.push_front(value) // insert value at front of
L - L.insert(pos, value) // insert value into L at
// position
indicated by iterator pos - L.front( ) // return L's first
element - L.back( ) // return L's last
element - L.begin( ) // return an iterator
positioned at start - L.end( ) // return the"past the
end" iterator - L.sort( ) // sort L's elements
using lt
Why not sort (L.begin( ), L.end( )) ?
30include ltlistgt include ltiostreamgt using
namespace std int main ( ) listltintgtL
L.push_back (9) L.push_back (7)
L.push_back (5) L.push_back (3)
listltintgtiterator p for (p L.begin ( )
p ! L.end ( ) p) cout ltlt p ltlt endl
for (p L.begin ( ) p ! L.end ( )
p) (p) for (p L.begin ( ) p !
L.end ( ) p) cout ltlt p ltlt endl return
0