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
2Agenda
- Templates
- IntArray vs. SimpleArray
- Containers and Iterators
- Vector Class
- Functors
- Generic Programming
3By the end of this class, you
- Need to
- Appreciate the need for templates
- Know how to implement and use templates
- Understand the concepts of Containers and
Iterators - Understand (broadly) the STL Vector code
- Ought to Know
- Do NOT Need to Know
- The precise working of every function in the
sample code
4Would you write this?
- void swap (int a, int b)
-
- int tmp a
- a b
- b tmp
-
5Would you write this?
- void swap (char a, char b)
-
- char tmp a
- a b
- b tmp
-
- void swap (int a, int b)
-
- int tmp a
- a b
- b tmp
-
6Or this?
- void swap (Some_type a, Some_type b)
-
- Some_type tmp a
- a b
- b tmp
-
7Templates
- Provide a way to re-use source code
- Two kinds of templates
- Class Templates
- Function Templates
- The compiler generates a specific class or
function from a template, referred to as template
instantiation - A class generated from a template is called a
generated class - A function generated from a template is called a
generated function
8Templates
- Common code for various data types.
- Generic data type.
- Syntax
- template lttypename Etypegt class SomeName
- template lttypename Etypegt function declaration
- Using templates
- Specify type compiler needs to know
- SomeNameltintgt variable_name
- Swapltchargt(c1, c2)
9Function Template swap( )
- template lttypename Tgt void swap (T a, T b)
-
- T tmp a
- a b
- b tmp
-
- swapltdoublegt(d1, d2)
10Class Template Array
- See Array wrapper class at /homesta/cs225/src/libr
ary/03-cgeneric/_simpleGenArray - templatelttypename Etypegt class SimpleArray
- //
- Etype operator (int index)
- //
- Etype data // Pointer to array elements.
-
- SimpleArrayltintgt integer_array
11Agenda
- Templates
- IntArray vs. SimpleArray (code in library)
- Containers and Iterators
- Vector Class
- Functors
- Generic Programming
12SimpleArray Things to Note
- template lttypename Etypegt goes at the beginning
of the class and every function defn. - template ltclass Etypegt is equivalent
- 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
13Agenda
- Templates
- IntArray vs. SimpleArray
- Containers and Iterators
- Vector Class
- Functors
- Generic Programming
14Containers
- A container is an object that holds other objects
- Examples are Arrays, Vectors, and Lists
- In general, you can add objects to containers, or
remove objects from containers - The C Standard Library (STL) has been designed
so that containers support standard operations /
provide common functionality.
15Iterators
- Iterators are generalizations of pointers for
containers - Iterators are NOT general pointers!
- They are an 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
16Categories of Iterators
- Based on access types
- Input
- Output
- Forward
- Bidirectional access
- Random access
- There is a natural hierarchy among these
17Iterator Categories and Operations
18Common Functions for (almost) all STL containers
16.3
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
19More Functions
Stack and Queue Operations
push_back( ) Add to the end pop_back( )
Remove the last element push_front( ) Add new
first element (used for list only) pop_front(
) Remove first element (should be used for list
only)
List Operations
insert(p, x) Add x before p insert(p,
n, x) Add n copies of x before p insert(p,
first,last) Add elements from firstlast
before p erase(p) Remove the
element at p erase(first, last) Erase
firstlast clear( ) Erase all the
elements
20More Functions
Other Operations
size( ) Number of elements empty(
) Is the container empty? max_size( )
Size of the largest possible
container capacity( ) Space allocated (vector
only) reserve( ) Reserve space for
future expansion (vector only) resize ( )
Change the size of the container swap( )
Swap elements of two containers
Are the contents of the two containers
the same? ! Are the contents
of the two containers different? lt
Is one container lexicographically before
another?
21More Functions
Constructors, etc
container( ) Empty
container container(n) n elements
default value container(n,x) n copies
of x container(first, last) Initial elements
from firstlast container(x) Copy
constructor container( ) Destroy
the container and all its elements
Assignments
operator(x) Copy assignment. assign(n,
x) Assign n copies of x assign(first,
last) Assign from firstlast
22Using Iterators
- templatelttypename Tgt void print_all(T c)
-
- typename Titerator i
- cout ltlt ""
- for (i c.begin() i ! c.end() i)
- cout ltlt i
- cout ltlt ""
-
23An example The IntArrayIter Class
24The IntArrayIter class
- 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
25Agenda
- Templates
- IntArray vs. SimpleArray
- Containers and Iterators
- Vector Class
- Functors
- Generic Programming
26The (modified) STL Vector class
Begin / Rend
End / Rbegin
2
5
4
6
1
start
finish
onePastEnd
size 5 capacity 8
27The (modified) STL Vector class
- 4 iterators
- iterator, reverse_iterator
- Their const versions
- Element access
- unchecked access
- at( ) checked access
- Rapid access, but expensive insert/delete (except
for push_back( ) and pop_back( ) )
28Agenda
- Templates
- IntArray vs. Array
- Containers and Iterators
- Vector Class
- Functors
- Generic Programming
29Function 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)
30A Functor Example
- templatelttypename Tgt class Sum
- private
- T res
- public
- Sum(T I0) res( I ) // init
- void operator( ) (T x) res x //
accumulate - T result( ) const return res // return sum
31An Accumulating function
- template lttypename It, typename Accgt
- void Accumulate (It first, It last, Acc
accumulate) -
- It temp
- for (temp first, temp ! last temp)
- accumulate(temp)
32Putting Them Together
- void random_accumulating_function
- (Vectorltintgt vi, Listltdoublegt ld)
-
- Sum s Product p
- Accumulate (vi.begin( ), vi.end( ), s)
- Accumulate (ld.begin( ), ld.end( ), p)
- cout ltlt s.result( ) ltlt p.result( )
33Alternatively
- templatelttypename Tgt class Product
- private
- T res
- public
- Product(T I1) res( I ) // init
- void operator( ) (T x) res x //
accumulate - T result( ) const return res // return sum
-
- void f (listltintgt ld)
- Product p
- p for_each(ld.begin( ), ld.end( ), p) //
include ltalgorithmgt - cout ltlt the product is ltlt p.result( ) ltlt
endl
34Agenda
- Templates
- IntArray vs. SimpleArray
- Containers and Iterators
- Vector Class
- Functors
- Generic Programming
35Generic 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 include copy(
), sort( ), binary_search( ), partition( )
36The _genericFns code
- Things to Note
- The print( ) function Just like Accumulate( )
- The printRelevant( ) function
- The function objects we use for formatting
- How to load the vector using push_back( )
- Looping through the Vector using iterators
- Calling the Generic print functions
- On a subset of the Vector
- Printing Relevant elements only
37Summary
- Templates
- IntArray vs. SimpleArray
- Containers and Iterators
- Vector Class
- Functors
- Generic Programming
- From an EWS machine
- /homesta/cs225/src/library/03-cgeneric/