Discussion Session 3: Generic Programming, Templates, Containers and Iterators - PowerPoint PPT Presentation

1 / 37
About This Presentation
Title:

Discussion Session 3: Generic Programming, Templates, Containers and Iterators

Description:

swap double (d1, d2); Class Template: Array ... (Vector int vi, List double ld) Sum s; Product p; Accumulate (vi.begin( ), vi.end( ), s) ... – PowerPoint PPT presentation

Number of Views:57
Avg rating:3.0/5.0
Slides: 38
Provided by: Nitish7
Category:

less

Transcript and Presenter's Notes

Title: Discussion Session 3: Generic Programming, Templates, Containers and Iterators


1
Discussion Session 3 Generic Programming,
Templates, Containers and Iterators
  • CS 225 Data Structures Software Principles

2
Agenda
  • Templates
  • IntArray vs. SimpleArray
  • Containers and Iterators
  • Vector Class
  • Functors
  • Generic Programming

3
By 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

4
Would you write this?
  • void swap (int a, int b)
  • int tmp a
  • a b
  • b tmp

5
Would 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

6
Or this?
  • void swap (Some_type a, Some_type b)
  • Some_type tmp a
  • a b
  • b tmp

7
Templates
  • 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

8
Templates
  • 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)

9
Function Template swap( )
  • template lttypename Tgt void swap (T a, T b)
  • T tmp a
  • a b
  • b tmp
  • swapltdoublegt(d1, d2)

10
Class 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

11
Agenda
  • Templates
  • IntArray vs. SimpleArray (code in library)
  • Containers and Iterators
  • Vector Class
  • Functors
  • Generic Programming

12
SimpleArray 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

13
Agenda
  • Templates
  • IntArray vs. SimpleArray
  • Containers and Iterators
  • Vector Class
  • Functors
  • Generic Programming

14
Containers
  • 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.

15
Iterators
  • 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

16
Categories of Iterators
  • Based on access types
  • Input
  • Output
  • Forward
  • Bidirectional access
  • Random access
  • There is a natural hierarchy among these

17
Iterator Categories and Operations
18
Common 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
19
More 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
20
More 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?
21
More 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
22
Using 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 ""

23
An example The IntArrayIter Class
24
The 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

25
Agenda
  • Templates
  • IntArray vs. SimpleArray
  • Containers and Iterators
  • Vector Class
  • Functors
  • Generic Programming

26
The (modified) STL Vector class
Begin / Rend
End / Rbegin
2
5
4
6
1
start
finish
onePastEnd
size 5 capacity 8
27
The (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( ) )

28
Agenda
  • Templates
  • IntArray vs. Array
  • Containers and Iterators
  • Vector Class
  • Functors
  • Generic Programming

29
Function 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)
30
A 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

31
An 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)

32
Putting 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( )

33
Alternatively
  • 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

34
Agenda
  • Templates
  • IntArray vs. SimpleArray
  • Containers and Iterators
  • Vector Class
  • Functors
  • Generic Programming

35
Generic 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( )

36
The _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

37
Summary
  • Templates
  • IntArray vs. SimpleArray
  • Containers and Iterators
  • Vector Class
  • Functors
  • Generic Programming
  • From an EWS machine
  • /homesta/cs225/src/library/03-cgeneric/
Write a Comment
User Comments (0)
About PowerShow.com