Title: Discussion Session 3: Generic Programming, Templates, Containers and Iterators
1Discussion Session 3 Generic Programming,
Templates, Containers and Iterators
- CS 225 Data Structures Software Principles
2Templates
3Swapping integers
- void swap (int a, int b)
-
- int tmp a
- a b
- b tmp
-
4Swapping characters
- void swap (char a, char b)
-
- char tmp a
- a b
- b tmp
-
- (repeat for types float, double, String, ?)
5Generic swapping
- We could just copy/paste. Why not?
- Code reuse is a Good Thing
- Waste of our time this is easy to automate
- It would be better if we could just specify a
generic type for swap ()
6Templates
- Provide a way to re-use source code
- Two kinds of templates
- Class Templates
- Function Templates
- The compiler generates specific code from
templates template instantiation - Using templates just means learning new syntax
7Function Template swap( )
- template lttypename Tgt
- void swap (T a, T b)
-
- T tmp a
- a b
- b tmp
-
- Use swap(foo1, foo2)
8Class Template SimpleArray
- See Array wrapper class at /homesta/cs225/src/libr
ary/03-cgeneric/_simpleGenArray - Declaration syntax
- templatelttypename Etypegt
- class SimpleArray
- //
- Etype operator (int index)
- //
- Etype data // Pointer to array elements.
-
9Class Template SimpleArray
- Definition syntax
- templatelttypename Etypegt
- SimpleArrayltEtypegtSimpleArray ()
-
- Instantiation syntax
-
- SimpleArrayltintgt intArray
10SimpleArray vs. IntArray
- Syntax changes
- Replace int with Etype
- Extra template syntax
- SimpleArray is not a type SimpleArrayltgt is
- SimpleArrayltintgt
- SimpleArrayltStringgt
- An array of Etypes is stored with a pointer to
Etype - Memory is allocated using new Etype
- Check _runThisCode for examples of use
11Containers and Iterators
12Containers
- A container is an object that holds other objects
- Examples Arrays, Vectors, Lists
- The C Standard Library (STL) was designed so
that containers have a standard interface - In general, you can add objects to containers, or
remove objects from containers - Iterators provide a general way to access the
stuff inside containers
13Iterators
- Iterators provide a way to access elements inside
a container - Abstraction of the idea of a pointer to an
element in a sequence - Iterators act as an interface between containers
and algorithms they hold them together by
providing an abstract view of the data
14Categories of Iterators
- Based on access types
- Input
- Output
- Forward
- Bidirectional access
- Random access
- In CS225, well use mainly Bidirectional access
- iterators
15Iterator Categories and Operations
16Common Functions for (almost) all STL Containers
Functions that return Iterators
begin( ) Points to first element end(
) Points to one-past-last
element rbegin( ) Points to first
element of reverse sequence rend( )
Points to one-past-last element of reverse
sequence
Element Access
front( ) First element back( ) Last element
Subscripting, unchecked access at(
) Subscripting, checked access
17Using Iterators
- templatelttypename Tgt
- void print_all(T c)
-
- Titerator i
- cout ltlt ""
- for (i c.begin() i ! c.end() i)
- cout ltlt i
- cout ltlt ""
-
18Example IntArrayIter
19Jasons IntArrayIteriterator class
- /homesta/cs225/src/library/03-cgeneric/_intIter
- // nested inside class IntArrayIter
- class iterator
-
- public
- iterator()
- int operator()
- IntArrayIteriterator operator() //
prefix - IntArrayIteriterator operator--() //
prefix - bool operator(IntArrayIteriterator
const origVal) const - // note not as full-featured as an STL iterator
implementation - private
- int ptr
- friend class IntArrayIter // so
IntArrayIter can set our private pointer -
- Iterator implementation just a wrapper around a
pointer
20Jasons IntArrayIter class
- class IntArrayIter
-
- public
- class iterator / see previous slide /
- //
- // same interface as the IntArray class, plus
- IntArrayIteriterator begin() // returns
itor to start of array - IntArrayIteriterator end() // returns itor
to one-past-the-end - private
- int lowerBound // lower bound
- int upperBound // upper bound
- int data // pointer to the start of the
array elements. - int onePastLast // pointer to the memory
one past end of array -
- end() is particularly useful when looping tells
us when were done - Understand implementations of these functions
the iterator class!
21IntArrayIter summary
- Things to Note
- The iterator class is nested in the IntArrayIter
class - We implement the iterator with an int
- How we implement the member functions via simple
pointer manipulation - The implementations of begin( ) and end( )
- The IntArray class has onePastEnd as a member
22The Vector class
23STL Class vector
- STL container that stores objects in a sequence,
with lower bound at 0 - Auto-expanding array (unlike the Array classes)
- Does this behind the scenes as necessary when you
add elements with push_back() or insert() - Runtime complexity amortized constant time for
access - Has 4 iterator types. Know how they are used.
- iterator, reverse_iterator, their const versions
24STL Class vector
begin() / rend()
end() / rbegin()
2
5
4
6
1
start
finish
onePastEnd
vectorSize 5 vectorCapacity 8
PRIVATE
- vectorSize how many elements the vector holds
- vectorCapacity how many elements the vector
could hold before expanding
25The (modified) STL Vector class
- 4 iterators
- iterator, reverse_iterator, const versions
- Element access
- unchecked access
- at( ) checked access
- Rapid access, but expensive insert/delete (except
for push_back( ) and pop_back( ) )
26iterator class in vector
- class iterator // iterator class nested inside
vector class - public
- // Bunch of typedefs, just like vector.
Useful when writing generic functions - iterator() // initalized to point to NULL
- reference operator()
- pointer operator-gt()
- iterator operator() // prefix
- iterator operator--() // prefix
- iterator operator(int ignore) // postfix
- iterator operator--(int ignore) // postfix
- bool operator(iterator const origVal) const
- bool operator!(iterator const origVal) const
- private
- pointer ptr
- iterator(pointer assignPtr)
- friend class vectorltvalue_typegt // so vector
can set private members - friend class vectorltvalue_typegtconst_iterator
// similarly -
27Function Objects
28Function Objects (Functors)
- Class objects that overload the ( ) operator for
implementing desired behavior - also ordinary function is a function object
- and so is a function pointer
- See Jasons _genericFns/ code!
class Negate public int operator() (int n)
return -n
void Callback(int n, Negate neg) int val
neg(n)
29A Functor Example
- templatelttypename Tgt class Sum
- private
- T res
- public
- Sum() res 0 // init
- void operator( ) (T x) res x
// accumulate - T result( ) const return res //
return sum -
- void getSum(vectorltdoublegt dVec)
- Sumltdoublegt s
- for(iterator iter dVec.begin() iter !
dVec.end() iter) - s(iter)
- cout ltlt "The sum is " ltlt s.result() ltlt endl
30More Examples
- /homesta/cs225/src/library/03-cgeneric/_genericF
ns - main.cpp
- 29-47 one way to load data into a vector
- 50-60 iterator loop you saw in class (almost)
- 62-78 calls to print() with different formatting
functors - 80-95 print a subset dont have to use
begin(), end() - 101-126 more functor fun with printRelevant()
- 126 same stuff, but with the Array class
31Generic Programming
32Generic Programming
- Decide which algorithms you want parameterize
them so that they work for a variety of suitable
types and data structures - Containers that are templated so they can hold
elements of any type - Generic algorithms which operate on containers
using iterators and assume nothing about the type
of object they contain. - Examples copy( ), sort( ), search( ),
partition( ), - How do templates, functors, iterators, etc.
support these ideas?
33Summary
- Templates
- IntArray vs. SimpleArray
- Containers and Iterators
- Vector Class
- Function Objects
- Generic Programming
- From an EWS machine
- /homesta/cs225/src/library/03-cgeneric/