CSE 332 Semester Review - PowerPoint PPT Presentation

Loading...

PPT – CSE 332 Semester Review PowerPoint presentation | free to download - id: 251160-YWViM



Loading


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation
Title:

CSE 332 Semester Review

Description:

Write up your notes pages as you study. Ask questions here and on the message board ... variable is known statically (at compile time), based on its declaration ... – PowerPoint PPT presentation

Number of Views:51
Avg rating:3.0/5.0
Slides: 58
Provided by: www1Cs
Category:
Tags: cse | review | semester | study | time

less

Write a Comment
User Comments (0)
Transcript and Presenter's Notes

Title: CSE 332 Semester Review


1
CSE 332 Semester Review
  • Goals for todays review
  • Review and summary of the material this semester
  • A chance to clarify and review key
    concepts/examples
  • Discuss details about the final exam
  • 330-530pm (2 hours) Friday May 6
  • Earth Planetary Sciences 203 (no longer Seigle
    304)
  • Two 8.5x11 faces of notes pencils/pens
    allowed
  • All electronics must be off, including cell
    phones, etc.
  • Recommendations for exam preparation
  • Catch up on any studio exercises youve not done
  • Write up your notes pages as you study
  • Ask questions here and on the message board

2
Lifecycle of a C Program
xterm
An IDE
window
console/terminal/window
Makefile
WebCAT
make
E-mail
turnin/checkin
make utility
Runtime/utility libraries (binary) .lib .a .dll
.so
Eclipse
compile
link
Visual Studio
C source code
Programmer (you)
debugger
precompiler
gcc, etc.
link
compiler
linker
executable program
compiler
object code (binary, one per compilation unit) .o
3
C Strings, C Strings, and Streams
  • include ltiostreamgt
  • include ltfstreamgt
  • include ltsstreamgt
  • using namespace std
  • int main (int, char)
  • ifstream ifs (in.txt)
  • if (ifs.is_open ())
  • string line_1, word_1
  • getline (ifs, line_1)
  • istringstream iss (line_1)
  • iss gtgt word_1
  • cout ltlt word_1 ltlt endl
  • return 0
  • ltsstreamgt header file
  • Use istringstream for input
  • Use ostringstream for output
  • Useful for scanning input
  • Get a line from file into string
  • Wrap string in a stream
  • Pull words off the stream
  • Useful for formatting output
  • Use string as format buffer
  • Wrap string in a stream
  • Push formatted values into stream
  • Output formatted string to file

4
Untangling Operator Syntax
5
Review Whats a Pointer?
  • A variable holding an address
  • Of what it points to in memory
  • Can be untyped
  • E.g., void v // points to anything
  • However, usually theyre typed
  • Checked by compiler
  • Can only be assigned addresses of variables of
    type to which it can point
  • E.g., int p // only points to int
  • Can point to nothing
  • E.g., p 0 // points to nothing
  • Can change where it points
  • As long as pointer itself isnt const
  • E.g., p i // now points to i

int i
7
0x7fffdad0
int p
6
Review Whats a Reference?
  • Also a variable holding an address
  • Of what it refers to in memory
  • But with a nicer interface
  • A more direct alias for the object
  • Hides indirection from programmers
  • Must be typed
  • Checked by compiler
  • Again can only refer to the type with which it
    was declared
  • E.g., int r i // refers to int i
  • Always refers to (same) something
  • Must initialize to refer to a variable
  • Cant change what it aliases

int i
7
0x7fffdad0
int r
7
Declarations with Pointers and References
  • Making something const says that a value cannot
    be changed through it
  • int p 0 p is a pointer to an integer
  • const int q 0 q is a pointer to an
    integer thats const
  • int const r 0 r is a pointer to a const
    integer (same as q, less common)
  • int const s 0 s is a const pointer to an
    integer (similar to an array)
  • const int const t 0 t is a const pointer
    to an integer thats const
  • const int u i u is a reference to an
    integer thats const
  • const int v q v is a reference to a
    pointer to an integer thats const
  • int const w s w is a reference to a const
    pointer to an integer
  • x is a reference to a const pointer to an
    integer thats const
  • const int const x t
  • Its ok for a const reference or pointer to
    access a non-const variable/object (but not the
    other way around)
  • const int i 7 // value of i cannot be changed
  • int j 7 // value of j can be changed

8
Pointer Arithmetic
  • You can subtract (but not add, multiply, etc.)
    pointers
  • Gives an integer with the distance between them
  • You can add/subtract an integer to/from a pointer
  • E.g., p(q-p)/2 is allowed but (pq)/2 gives an
    error
  • Note relationship between array and pointer
    arithmetic
  • Given pointer p and integer n, the expressions
    pn and (pn) are both allowed and mean the
    same thing
  • int main (int argc, char argv)
  • int arr 3 0, 1, 2
  • int p arr0
  • int q p 1
  • return 0

int arr 3
2
1
0
0x7fffdad0
0x7fffdaf0
int p
int q
9
How Function Calls Work
  • A function call uses the program call stack
  • Stack frame is pushed when the call is made
  • Execution jumps to the functions code block
  • Functions code block is executed
  • Execution returns to just after where call was
    made
  • Stack frame is popped (variables in it
    destroyed)
  • This incurs a (small) performance cost
  • Copying arguments, other info into the stack
    frame
  • Stack frame management
  • Copying function result back out of the stack
    frame

10
Pass By Value
  • void foo ()
  • int i 7
  • baz (i)
  • void baz (int j)
  • j 3

7
local variable i (stays 7)
Think of this as declaration with initialization,
along the lines of int j what baz was passed
parameter variable j (initialized with the value
passed to baz, and then is assigned the value 3)
7 ? 3
11
Pass By Reference
again declaration with initialization int j
what baz was passed
  • void foo ()
  • int i 7
  • baz (i)
  • void baz (int j)
  • j 3

7 ? 3
local variable i
j is initialized to refer to the variable
that was passed to baz when j is assigned 3, the
passed variable is assigned 3.
7 ? 3
argument variable j
12
Default Arguments
  • Watch out for ambiguous signatures
  • foo() and foo(int a 2) for example
  • Can only default the rightmost arguments
  • Cant declare void foo(int a 1, int b)
  • Caller must supply leftmost arguments
  • Even if theyre the same as the defaults

13
Overview of C Exceptions
  • Normal program control flow is halted
  • At the point where an exception is thrown
  • The program call stack unwinds
  • Stack frame of each function in call chain pops
  • Variables in each popped frame are destroyed
  • This goes on until an enclosing try/catch scope
    is reached
  • Control passes to first matching catch block
  • Can handle the exception and continue from there
  • Can free some resources and re-throw exception

14
Rules of Thumb for C Exceptions
  • Use exceptions to handle any cases where the
    program cannot behave normally
  • Put more specific catch blocks before more
    general
  • Don't let a thrown exception propagate out of
    main
  • Instead, always catch any exceptions that
    propagate up
  • Then return a non-zero value to indicate program
    failure
  • Do not use or rely on exception specifications
  • A false promise if you declare them, unless you
    have fully checked all the code used to implement
    that interface
  • No guarantees that they will work for templates,
    because a template parameter could leave them off
    and then throw

15
Classes, Structs, and Access Permissions
  • Declaring access control scopes within a class
  • private visible only within the class
  • protected also visible within derived classes
    (more later)
  • public visible everywhere
  • Access control in a class is private by default
  • but, its better style to label access control
    explicitly
  • A struct is the same as a class, except
  • Access control for a struct is public by default
  • Usually used for things that are mostly data
  • E.g., if initialization and deep copy only, may
    suggest using a struct
  • Versus classes, which are expected to have both
    data and some form of non-trivial behavior
  • E.g., if reference counting, etc. probably want
    to use a class

16
Static Class Members
Date Datedefault_date(1, 1, 2004) void
Dateset_default(int m, int d, int
y) Datedefault_date Date(m, d, y)
class Date public // ... static void
set_default(int,int,int) private int _d, _m,
_y static Date default_date DateDate
() _d (default_date._d), _m
(default_date._m), _y (default_data._y) Date
operator (const Date d) this-gtd_ d.d_
this-gtm_ d.m_ this-gty_ d.y_
  • Must define static members, usually outside of
    class
  • Initialized before any functions in same
    compilation unit are called
  • Static member functions dont get implicit this
    parameter
  • Cant see non-static class members
  • But non-static member functions can see static
    members

17
Default and Copy Constructors
  • Default constructor takes no arguments
  • Can supply default values via base/member list
  • Must do this for const and reference members
  • Compiler synthesizes one if no constructors are
    provided
  • Does default construction of all class members
    (a.k.a member-wise)
  • Copy constructor takes a reference to a class
    instance
  • Compiler provides one by default if you dont
  • Does (shallow) copy construction of all class
    members
  • If you dont want compiler to generate one of
    them
  • Declare private, dont define, dont use within
    class
  • But, its usually best do declare and define both
    of these
  • Default / copy construction of built-in types
  • Default construction does nothing (leaves
    uninitialized)
  • Copy construction fills in the value given

18
Destructors
  • Constructors initialize objects
  • At start of objects lifetime
  • implicitly called when object is created (can
    also call explicitly)
  • Often want to make destructors virtual
  • More on this when we discuss inheritance
  • Destructors clean up afterward
  • Compiler provides if you dont
  • Does member-wise destruction
  • Destructor is implicitly called when an object is
    destroyed
  • Can make destructor private, call it from within
    a member function
  • e.g., a public one called destroy()
  • Why would you want to do this?

class Calendar public Calendar (size_t
s) virtual Calendar () // etc ...
private size_t size_ Date
dates_ CalendarCalendar (size_t s)
size_(s), dates_(0) if (size_ gt 0)
dates_ new Datesize_ CalendarCalend
ar () delete dates_
19
Assignment Operator
  • Compiler supplies if you dont
  • Does member-wise assignment
  • Similar to copy constructor
  • But must deal with the existing values of
    objects members
  • And, no initialization list
  • Watch out for self-reference
  • Assignment of an object to itself
  • s s // perfectly legal syntax
  • Efficiency, correctness issues
  • Watch out for correct aliasing and copying cost
    trade-offs
  • Copying an int vs. an int vs. an int vs. an
    int
  • Can leverage copy constructor to ensure safe
    reallocation
  • More on these issues throughout the semester

class Array public Array(unsigned int)
Array(const Array ) Array() Array
operator(const Array a) private int
ints_ size_t size_ Array
Arrayoperator(const Array a) if (a !
this) Array temp(a)
stdswap(temp.ints_, ints_)
stdswap(temp.size_, size_) return
this
20
Public, Protected, Private Inheritance
  • class A
  • public
  • int i
  • protected
  • int j
  • private
  • int k
  • Class B public A
  • // ...
  • Class C protected A
  • // ...
  • Class D private A
  • // ...
  • Class A declares 3 variables
  • i is public to all users of class A
  • j is protected. It can only be used by methods
    in class A or its derived classes ( friends)
  • k is private. It can only be used by methods in
    class A ( friends)
  • Class B uses public inheritance from A
  • i remains public to all users of class B
  • j remains protected. It can be used by methods in
    class B or its derived classes
  • Class C uses protected inheritance from A
  • i becomes protected in C, so the only users of
    class C that can access i are the methods of
    class C
  • j remains protected. It can be used by methods in
    class C or its derived classes
  • Class D uses private inheritance from A
  • i and j become private in D, so only methods of
    class D can access them.

21
Class and Member Construction Order
  • class A
  • public
  • A(int i) m_i(i)
  • cout ltlt "A ltlt endl
  • A() coutltlt"A"ltltendl
  • private
  • int m_i
  • class B public A
  • public
  • B(int i, int j)
  • A(i), m_j(j)
  • cout ltlt B ltlt endl
  • B() cout ltlt B ltlt endl
  • private
  • int m_j
  • int main (int, char )
  • B b(2,3)
  • In the main function, the B constructor is called
    on object b
  • Passes in integer values 2 and 3
  • B constructor calls A constructor
  • passes value 2 to A constructor via base/member
    initialization list
  • A constructor initializes m_i
  • with the passed value 2
  • Body of A constructor runs
  • Outputs A
  • B constructor initializes m_j
  • with passed value 3
  • Body of B constructor runs
  • outputs B

22
Class and Member Destruction Order
  • class A
  • public
  • A(int i) m_i(i)
  • cout ltlt "A ltlt endl
  • A() coutltlt"A"ltltendl
  • private
  • int m_i
  • class B public A
  • public
  • B(int i, int j) A(i), m_j(j)
  • cout ltlt B ltlt endl
  • B() cout ltlt B ltlt endl
  • private
  • int m_j
  • int main (int, char )
  • B b(2,3)
  • return 0
  • B destructor called on object b in main
  • Body of B destructor runs
  • outputs B
  • B destructor calls destructor of m_j
  • int is a built-in type, so its a no-op
  • B destructor calls A destructor
  • Body of A destructor runs
  • outputs A
  • A destructor calls destructor of m_i
  • again a no-op
  • Compare orders of construction and destruction of
    base, members, body
  • at the level of each class, order of steps is
    reversed in constructor vs. destructor
  • ctor base class, members, body
  • dtor body, members, base class

23
C Polymorphism
  • Public inheritance creates sub-types
  • Inheritance only applies to user-defined classes
    (and structs)
  • A publicly derived class is-a subtype of its base
    class
  • Known as inheritance polymorphism
  • Depends on dynamic typing
  • Virtual member function/operator, base
    pointer/reference to derived object
  • Template parameters also induce a subtype
    relation
  • Known as interface polymorphism
  • Well cover how this works in-depth after the
    midterm exam
  • Liskov Substitution Principle (for both kinds of
    polymorphism)
  • if S is a subtype of T, then wherever you need a
    T you can use an S

24
Static vs. Dynamic Type
  • The type of a variable is known statically (at
    compile time), based on its declaration
  • int i int p
  • Fish f Mammal m
  • Fish fp f
  • However, actual types of objects aliased by
    references pointers to base classes vary
    dynamically (at run-time)
  • Fish f Mammal m
  • Animal ap f
  • ap m
  • Animal ar get_animal()

Animal
Fish
Mammal
  • A base class and its derived classes form a set
    of types
  • type(ap) ? Animal, Fish, Mammal
  • typeset(fp) ? typeset(ap)
  • Each type set is open
  • More subclasses can be added

25
Potential Problem Class Slicing
  • Catch derived exception types by reference
  • Also pass derived types by reference
  • Otherwise a temporary variable is created
  • Loses original exceptions dynamic type
  • Results in the class slicing problem where only
    the base class parts and not derived class parts
    copy

26
Function Overloading
  • class A
  • public
  • int add(int i, int j)
  • // not allowed, would be
  • // ambiguous with above
  • // long add(int m, int n)
  • // Ok, different signature
  • long add(long m, long n)
  • int
  • main (int argc, char argv)
  • int a 7
  • int b 8
  • int c add(a, b)
  • return 0
  • Calls to overloaded functions and operators are
    resolved by
  • Finding all possible matches based on passed
    arguments
  • May involve type promotion
  • May involve instantiating templates
  • Finding the best match among those possible
    matches
  • Signature does not include the return type
  • Which might not help even if it did, i.e., calls
    may ignore result
  • So, overloading cant be resolved by return type
    alone
  • Compiler generates an error if the call cant be
    resolved

27
Operator Overloading
  • class A
  • friend ostream operatorltlt
  • (ostream , const A )
  • private
  • int m_a
  • ostream operatorltlt
  • (ostream out, const A a)
  • out ltlt "Am_a " ltlt a.m_a
  • return out
  • int main ()
  • A a
  • cout ltlt a ltlt endl
  • return 0
  • Similar to function overloading
  • Resolved by signature
  • Best match is used
  • But the list of operators and the arity of each
    is fixed
  • Cant invent operators
  • Must use same number of arguments as for built-in
    types (except for operator())
  • Operator precedence also is fixed when
    overloading
  • Some operators are off limits
  • (scope) . (dot) ? (conditional)
  • sizeof typeid (RTTI)
  • type casting operators

28
Memory Segments
  • 4 major memory segments
  • Global variables outside stack, heap
  • Code (a.k.a. text) the compiled program
  • Heap dynamically allocated variables
  • Stack parameters, automatic and temporary
    variables
  • Key differences from Java
  • Destructors of automatic variables called when
    stack frame where declared pops
  • Destructors of temporary variables called when
    they go out of scope as well
  • No garbage collection program must explicitly
    free dynamic memory
  • Heap and stack use varies dynamically
  • Code and global use is fixed
  • Code segment is read-only


stack



heap

code
global

29
Memory, Lifetimes, and Scopes
  • Temporary variables
  • Are scoped to an expression, e.g., a b 3 c
  • Automatic (stack) variables
  • Are scoped to the duration of the function in
    which they are declared
  • Dynamically allocated variables
  • Are scoped from explicit creation (new) to
    explicit destruction (delete)
  • Global variables
  • Are scoped to the entire lifetime of the program
  • Includes static class and namespace members
  • May still have initialization ordering issues
    (Singleton Pattern)
  • Member variables
  • Are scoped to the lifetime of the object within
    which they reside
  • Depends on whether object is temporary,
    automatic, dynamic, or global
  • Lifetime of a pointer/reference can differ from
    the lifetime of the location to which it
    points/refers

30
Scopes and Memory Management Mistakes
  • Variables and the pointers and references to them
    may have different scopes
  • May result in obvious kinds of lifetime errors we
    saw earlier
  • But may also introduce more subtle issues of
    aliasing
  • Still can risk destroying an object too soon or
    too late
  • Card a_card //? stack object
  • Destructor will be implicitly called when a_card
    is out of scope.
  • Card card_ptr new Card //? heap object
  • Requires explicit delete
  • Dont do these
  • delete a_card // delete on a stack object
  • a_card (new Card) // using new to get a
    temporary variable
  • Also avoid these kinds of errors
  • Returning a pointer or reference to an object
    that goes out of scope
  • Deleting the same object twice, or not at all

31
C Memory Management Idioms
  • Idioms are reusable design techniques in a
    language
  • Well look at 4 important ones in C
  • Copy constructor trick for assignment
  • Ensures release of existing resource and
    acquisition of the new resource both succeed or
    fail together
  • RAII (a.k.a. Guard, implemented by auto_ptr)
  • ties dynamic resources to other (esp. automatic)
    scopes
  • Reference counting
  • ties dynamic lifetime to a group of references
  • Copy-on-write
  • allows more efficient management of multiple
    aliasing

32
C STL Generic Programming Example
  • include ltiostreamgt
  • include ltiteratorgt
  • include ltalgorithmgt


  • using namespace std

  • int main (int, const char )

  • int numbers 0, 9, 2, 7, 4, 5, 6, 3, 8,
    1


  • size_t array_dimension sizeof (numbers) /
    sizeof (int)
  • // prints out 0 1 2 3 4 5 6 7 8 9 (ascending
    sort)
  • sort (numbers, numbers array_dimension)
  • copy (numbers, numbers array_dimension,
    ostream_iteratorltintgt(cout, " "))
  • cout ltlt endl
  • // prints out 9 8 7 6 5 4 3 2 1 0 (descending
    sort)

  • sort (numbers, numbers array_dimension,
    greaterltintgt())
  • copy (numbers, numbers array_dimension,
    ostream_iteratorltintgt(cout, " "))
  • cout ltlt endl

33
Function Templates
  • template lttypename Tgt
  • void swap(T lhs,
  • T rhs)
  • T temp lhs
  • lhs rhs
  • rhs temp
  • int main ()
  • int i 3
  • int j 7
  • long r 12
  • long s 30
  • swap (i, j)
  • // i is now 7, j is now 3
  • swap (r, s)
  • // r is now 30, s is now 12
  • return 0
  • The swap function template takes a single type
    parameter, T
  • interchanges values of two passed arguments of
    the parameterized type
  • Compiler instantiates the function template twice
    in main
  • with type int for the first call
  • with type long for the second call
  • Note that the compiler infers the type each time
    swap is called
  • Based on the types of the arguments

34
Class Templates
  • template lttypename Tgt
  • class Array
  • public
  • Array(const int size)
  • Array()
  • const int size () const
  • private
  • T m_values
  • const int m_size
  • int main (int, char)
  • Array ltintgt a(10)
  • return 0
  • Start with a simple declaration
  • Which well expand as we go
  • Notice that parameterized type T is used within
    the class template
  • Type of pointer to array
  • When an instance is declared, must also
    explicitly specify the concrete type parameter
  • E.g., int in function main (int, char)

35
Templates Introduce Interface Polymorphism
  • Can plug in any types for which templates
    syntactic use is valid (get a compiler error if
    not)
  • Templates apply to types that provide a common
    interface
  • What needs to be common depends on the template
  • Templates impose requirements on type parameters
  • Each requirement consists of a C expression
    that must be valid for that types involved in
    that expression
  • e.g., if a templates code has Z z Z must allow
    default construction
  • Interface polymorphism still allows Liskov
    Substitution
  • If S models a subset of the requirements modeled
    by T then wherever you need an S you can plug in
    a T
  • Much more on this in the next several lectures

36
Concepts and Models
  • Templates impose requirements on type parameters
  • Types that are plugged in must meet those
    requirements
  • Otherwise, the code wont compile (and errors
    will say why)
  • The set of requirements imposed is called a
    concept
  • Any specific type that meets the requirements is
    a model of that concept
  • What requirement(s) does the expression
    return first impose?
  • What about
  • while(first ! last first ! value)
  • first

Iterator
const T
37
Interface Polymorphism Concept Refinement
  • A concept C is a refinement of concept D if C
    imposes all of the requirements of D
  • Modeling and refinement satisfy three formal
    properties
  • Reflexivity A concept refines itself
  • Containment if T models C and C refines D then T
    models D
  • Transitivity If C refines D then C refines any
    concept D refines
  • What in the OO paradigm is this like? How does
    it differ?

C0
transitivity
C1
T1
T2
C2
containment
T3
T4
can substitute, e.g., T3 for T1
38
Associated Types
  • template lttypename Tgt
  • class Array public ArrayBase
  • public
  • typedef T iterator
  • Array(const int size)
  • Array()
  • iterator begin ()
  • return m_values
  • iterator end ()
  • return m_valuesm_size
  • private
  • T m_values
  • void foo
  • Arrayltintgt a
  • fill_array(a)
  • for (Arrayltintgtiterator i a.begin() i !
    a.end() i)
  • cout ltlt i ltlt ltlt endl
  • A type parameter is not concrete until its
    instantiated
  • The compiler can work around that in many cases
  • But sometimes the compiler needs more information
  • Additional information can be associated with a
    type
  • For example, a class template can define an
    iterator type
  • Available to the template and code that uses the
    template

39
Template Specialization More Polymorphism
  • typedef char charptr
  • typedef int intptr
  • template ltgt void print
  • (ostream os, const char message,
  • const bool b)
  • os ltlt message ltlt stdboolalpha
  • ltlt b ltlt endl
  • template ltgt void print
  • (ostream os, const char message,
  • const charptr s)
  • os ltlt message
  • ltlt reinterpret_castltvoid gt (s)
  • if (s ! 0)
  • os ltlt " (points to \""
  • ltlt s ltlt "\")"
  • os ltlt endl
  • template ltgt void print

template lttypename Tgt void print (ostream os,
const char message, const
T t) os ltlt message ltlt t ltlt endl
  • Specialize on individual types
  • bool char int
  • Notice the use of typedef
  • With specialization, we get
  • i is 7
  • b is false
  • ip is 0xfeebf064 (points to 7)
  • cp is 0x8048c30 (points to "hello, world!")
  • vp is 0x8048c30
  • And, we can reuse the solution!

40
Container Concepts
Container
  • Notice containers can have multiple
    classifications
  • Useful to look at differences between data
    structures!
  • Back vs. front insertion
  • Forward vs. reversible vs. random access
  • More general concepts higher in the hierarchy
  • More specific concepts appear farther down

Forward Container
Sequence
list
Reversible Container
Front Insertion Sequence
Back Insertion Sequence
Random Access Container
deque
vector
refined by
models
41
Overview of STL Iterators
  • STL iterators generalize different uses of
    pointers
  • Interface between algorithms and data structures
  • Algorithm manipulates iterators, not containers
  • STL iterators value can represent 3 kinds of
    states
  • Dereferenceable (points to a valid location in a
    range)
  • Past the end (points just past last valid
    location in a range)
  • Singular (points to nothing)
  • Whats an example of a pointer in each of these
    states?
  • STL iterators may be compared for equality
  • STL iterators may be copied and assigned
  • Why are STL iterators designed this way?

42
A Closer Look at STL Ranges
  • char find(char start, char end, char c)
  • while (start ! end start ! c)
  • start
  • return start
  • searches all positions in the string (from start
    up to but not including end) for a position with
    value c
  • A closed/open range start, end)
  • A few questions about ranges to consider
  • At what position is \0 in hello ?
  • What is the last element in 0,1) ?
  • Closed/open ranges help avoid off-by-one errors
  • The number of elements in the range start, end)
    is end - start

43
Some Definitions Related to Ranges
  • A valid range can be traversed safely with an
    iterator
  • An empty range p,p) is valid
  • If first, last) is valid and non-empty, then
    first1, last) is also valid
  • Proof iterative induction on the range
  • Iffirst, last) is valid
  • and position mid is reachable from first
  • and last is reachable from mid
  • then first, mid) and mid, last) are also valid
  • If first, mid) and mid, last) are valid, then
    first, last) is valid
  • Proof divide and conquer induction on range

44
Iterator Concept Hierarchy
transient write to stream (ostream)
destructive read at head of stream (istream)
  • read or write a value (one-shot)

Input Iterator
Output Iterator
Linked-list style access (slist)
  • value persists after read/write
  • values have locations
  • can express distance between two iterators

Forward Iterator
Bi-linked-list style access (list)
Bidirectional Iterator
Array/buffer style access (vector, deque)
Random Access Iterator
45
Matching an Algorithm to the Iterators it Needs
What STL iterator category does find require?
46
Iterators/Algorithms Match via Type Programming
  • Associated types (the idea)
  • Let you associate a type with another type
  • Given a type parameter, let you get the other
    type
  • Let you control encapsulation of type information
  • Typedefs specialization (the mechanisms)
  • Let you give a known type another name
  • Let you name associated types consistently
  • Across user-defined/built-in const/non-const
    types
  • Traits (the technique)
  • Let you associate user-defined and built-in types
  • Let you provide consistent access across types

47
Associated Types (the Idea)
  • Want to swap the values of two locations in
    memory
  • Basic idea is simple
  • Declare a temporary variable
  • Remember value from location i1 aliases in temp
  • Copy value from location i2 aliases into location
    i1 aliases
  • Copy remembered value from temp into location
    i2 aliases
  • But, code to left wont compile
  • How can we declare temps type?
  • How can we get T from I?

// Based on Austern pp. 34 template lttypename
Igt void swap (I i1, I i2) T temp i1 i1
i2 i2 temp
48
Typedef Specialization (the Mechanisms)
// Based on Austern, pp. 35 template lttypename
Igt struct iterator_traits typedef typename
Ivalue_type value_type template
lttypename Tgt struct iterator_traitsltTgt
typedef T value_type template lttypename
Tgt struct iterator_traitsltconst Tgt typedef T
value_type
  • Use specialization of a general traits struct
    template
  • Still have to parameterize struct iterator_traits
    with typename I
  • Cant do full specialization since were using
    type parameter T
  • Gives us different versions of the
    iterator_traits struct
  • For user-defined, built-in types
  • For const, non-const types
  • Remember that the C compiler will select the
    most specific match

49
Traits (the Technique)
template lttypename Igt void swap (I i1, I i2)
iterator_traitsltIgtvalue_type temp i1
i1 i2 i2 temp
  • Given the iterator type I
  • Traits provide an interface to Is associated
    types
  • E.g., iterator_traitsltIgtvalue_type
  • Let us obtain and use those types in template
    code
  • In general, let us go from containers to
    iterators to traits to associated types
  • Even within templates

50
Iterator Traits and Category Type Tags
struct input // empty structs for type
tags struct output struct fwd public input
// note inheritance struct bidir public fwd
struct rand public bidir template
lttypename Igt struct iterator_traits ...
typedef typename Iiterator_category
iterator_category template lttypename Tgt
struct iterator_traitsltTgt ... typedef rand
iterator_category template lttypename
Tgt struct iterator_traitsltconst Tgt ...
typedef rand iterator_category
  • Need a few concrete types to use as tags
  • E.g., empty structs
  • E.g., input, output, fwd, bidir, and rand
  • Tags provide yet another associated type for
    iterators
  • Iterator category
  • Again, made available by using the traits idiom

(actually, random_access_iterator_tag)
51
Algorithm Dispatching via Category Tags
  • Static dispatching
  • Implementations provide different signatures
  • Iterator type is evaluated at compile-time
  • Links to the best implementation
  • Notice how type tags are used

// Based on Austern, pp. 38, 39 template ltclass
Iter, class Distancegt void move (Iter i,
Distance d, fwd) while (dgt0) --d i //
O(d) template ltclass Iter, class Distancegt
void move (Iter i, Distance d, rand) i d
// O(1) template ltclass Iter, class Distancegt
void move (Iter i, Distance d) move (i, d,
iterator_traitsltItergt iterator_categor
y() )
concrete tag (empty struct) type
concrete tag (empty struct) type
explicit constructor call
52
Organization of Algorithms within the STL
  • The ltalgorithmgt header file contains
  • Non-modifying sequence operations
  • Do some calculation but dont change sequence
    itself
  • Examples include count, count_if
  • Mutating sequence operations
  • Modify the order or values of the sequence
    elements
  • Examples include copy, random_shuffle
  • Sorting and related operations
  • Modify the order in which elements appear in a
    sequence
  • Examples include sort, next_permutation
  • The ltnumericgt header file contains
  • General numeric operations
  • Scalar and matrix algebra, especially used with
    vectorltTgt
  • Examples include accumulate, inner_product

53
STL Functor Concept Hierarchy
Assignable
is-refined-by
Generator
Binary Function
Unary Function
Adaptable Generator
Binary Predicate
Adaptable Binary Function
Random Number Generator
Predicate
Adaptable Unary Function
Hash Function
Adaptable Predicate
Adaptable Binary Predicate
Strict Weak Ordering
Basic Function Object
Predicate
Specialized
Adaptable Function Object
54
Member Function Adaptor Example
  • struct B virtual void print() 0
  • struct D1 public B
  • void print() cout ltlt "I'm a D1" ltlt endl
  • struct D2 public B
  • void print() cout ltlt "I'm a D2" ltlt endl
  • int main(int, char )
  • vectorltBgt v
  • v.push_back(new D1) v.push_back(new D2)
  • v.push_back(new D2) v.push_back(new D1)
  • for_each(v.begin(), v.end(), mem_fun(
    Bprint))
  • return 0

55
Whats a Design Pattern?
  • A design pattern has a name
  • So when someone says Adapter you know what they
    mean
  • So you can communicate design ideas as a
    vocabulary
  • A design pattern describes the core of a solution
    to a recurring design problem
  • So you dont have to reinvent known design
    techniques
  • So you can benefit from others (and your) prior
    experience
  • A design pattern is capable of generating many
    distinct design decisions in different
    circumstances
  • So you can apply the pattern repeatedly as
    appropriate
  • So you can work through different design problems
    using it

56
Design Patterns Summary
  • Weve looked at a number of design patterns
  • Iterator access elements sequentially no matter
    how stored
  • Factory method create a related type
    polymorphically
  • Adapter converts an interface you have into one
    you want
  • Memento externalizes the state of an object
  • Observer tells objects about changes in another
    object
  • Singleton provides access to a single instance
  • Prototype polymorphic duplication of
    heterogeneous types
  • Visitor allows interaction with heterogeneous
    collections
  • Whats important to know about each pattern
  • Its name
  • What problem it solves and when to apply it
  • How it solves that problem (in a reasonable level
    of detail)

57
CSE 332 Final Exam
  • 330-530pm Friday May 6
  • Relocated to Earth Planetary Sciences 203
    (moved from Seigle 304)
  • Two 8.5x11 faces of notes pencils/pens
    allowed
  • Electronics must be off, including cell phones,
    etc.
  • Recommendations for exam preparation
  • Catch up on any studio exercises youve not done
  • Write up your notes pages as you study
  • Ask questions on the message board
About PowerShow.com