CSE 332 Semester Review - PowerPoint PPT Presentation


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


The Adobe Flash plugin is needed to view this content

Get the plugin now

View by Category
About This Presentation

CSE 332 Semester Review


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
Tags: cse | review | semester | study | time


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

Title: CSE 332 Semester Review

CSE 332 Semester Review
  • Goals for todays review
  • Review and summary of the material this semester
  • A chance to clarify and review key
  • Discuss details about the final exam
  • 330-530pm (2 hours) Friday May 6
  • Earth Planetary Sciences 203 (no longer Seigle
  • Two 8.5x11 faces of notes pencils/pens
  • 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

Lifecycle of a C Program
make utility
Runtime/utility libraries (binary) .lib .a .dll
Visual Studio
C source code
Programmer (you)
gcc, etc.
executable program
object code (binary, one per compilation unit) .o
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

Untangling Operator Syntax
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
int p
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
int r
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

Pointer Arithmetic
  • You can subtract (but not add, multiply, etc.)
  • 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
  • Note relationship between array and pointer
  • 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
int p
int q
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
  • Stack frame is popped (variables in it
  • This incurs a (small) performance cost
  • Copying arguments, other info into the stack
  • Stack frame management
  • Copying function result back out of the stack

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

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

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

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
  • Don't let a thrown exception propagate out of
  • Instead, always catch any exceptions that
    propagate up
  • Then return a non-zero value to indicate program
  • 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

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

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
  • Initialized before any functions in same
    compilation unit are called
  • Static member functions dont get implicit this
  • Cant see non-static class members
  • But non-static member functions can see static

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
  • Does default construction of all class members
    (a.k.a member-wise)
  • Copy constructor takes a reference to a class
  • Compiler provides one by default if you dont
  • Does (shallow) copy construction of all class
  • If you dont want compiler to generate one of
  • Declare private, dont define, dont use within
  • But, its usually best do declare and define both
    of these
  • Default / copy construction of built-in types
  • Default construction does nothing (leaves
  • Copy construction fills in the value given

  • 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
  • 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_
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
  • Copying an int vs. an int vs. an int vs. an
  • Can leverage copy constructor to ensure safe
  • 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
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.

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

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

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
  • Known as inheritance polymorphism
  • Depends on dynamic typing
  • Virtual member function/operator, base
    pointer/reference to derived object
  • Template parameters also induce a subtype
  • Known as interface polymorphism
  • Well cover how this works in-depth after the
    midterm exam
  • Liskov Substitution Principle (for both kinds of
  • if S is a subtype of T, then wherever you need a
    T you can use an S

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

  • 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

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

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
  • May involve type promotion
  • May involve instantiating templates
  • Finding the best match among those possible
  • 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
  • Compiler generates an error if the call cant be

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
  • Some operators are off limits
  • (scope) . (dot) ? (conditional)
  • sizeof typeid (RTTI)
  • type casting operators

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




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

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

C Memory Management Idioms
  • Idioms are reusable design techniques in a
  • 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)
  • Reference counting
  • ties dynamic lifetime to a group of references
  • Copy-on-write
  • allows more efficient management of multiple

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,

  • size_t array_dimension sizeof (numbers) /
    sizeof (int)
  • // prints out 0 1 2 3 4 5 6 7 8 9 (ascending
  • 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 (numbers, numbers array_dimension,
  • copy (numbers, numbers array_dimension,
    ostream_iteratorltintgt(cout, " "))
  • cout ltlt endl

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

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)

Templates Introduce Interface Polymorphism
  • Can plug in any types for which templates
    syntactic use is valid (get a compiler error if
  • Templates apply to types that provide a common
  • 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
  • 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

Concepts and Models
  • Templates impose requirements on type parameters
  • Types that are plugged in must meet those
  • Otherwise, the code wont compile (and errors
    will say why)
  • The set of requirements imposed is called a
  • 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

const T
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
  • 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?

can substitute, e.g., T3 for T1
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
  • The compiler can work around that in many cases
  • But sometimes the compiler needs more information
  • Additional information can be associated with a
  • For example, a class template can define an
    iterator type
  • Available to the template and code that uses the

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!

Container Concepts
  • Notice containers can have multiple
  • Useful to look at differences between data
  • 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
Reversible Container
Front Insertion Sequence
Back Insertion Sequence
Random Access Container
refined by
Overview of STL Iterators
  • STL iterators generalize different uses of
  • Interface between algorithms and data structures
  • Algorithm manipulates iterators, not containers
  • STL iterators value can represent 3 kinds of
  • Dereferenceable (points to a valid location in a
  • 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
  • STL iterators may be compared for equality
  • STL iterators may be copied and assigned
  • Why are STL iterators designed this way?

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

Some Definitions Related to Ranges
  • A valid range can be traversed safely with an
  • 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

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
Matching an Algorithm to the Iterators it Needs
What STL iterator category does find require?
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
  • 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
  • Traits (the technique)
  • Let you associate user-defined and built-in types
  • Let you provide consistent access across types

Associated Types (the Idea)
  • Want to swap the values of two locations in
  • 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
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
  • Use specialization of a general traits struct
  • 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

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
  • E.g., iterator_traitsltIgtvalue_type
  • Let us obtain and use those types in template
  • In general, let us go from containers to
    iterators to traits to associated types
  • Even within templates

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
  • Iterator category
  • Again, made available by using the traits idiom

(actually, random_access_iterator_tag)
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
Organization of Algorithms within the STL
  • The ltalgorithmgt header file contains
  • Non-modifying sequence operations
  • Do some calculation but dont change sequence
  • Examples include count, count_if
  • Mutating sequence operations
  • Modify the order or values of the sequence
  • Examples include copy, random_shuffle
  • Sorting and related operations
  • Modify the order in which elements appear in a
  • Examples include sort, next_permutation
  • The ltnumericgt header file contains
  • General numeric operations
  • Scalar and matrix algebra, especially used with
  • Examples include accumulate, inner_product

STL Functor Concept Hierarchy
Binary Function
Unary Function
Adaptable Generator
Binary Predicate
Adaptable Binary Function
Random Number Generator
Adaptable Unary Function
Hash Function
Adaptable Predicate
Adaptable Binary Predicate
Strict Weak Ordering
Basic Function Object
Adaptable Function Object
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(
  • return 0

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

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
  • Adapter converts an interface you have into one
    you want
  • Memento externalizes the state of an object
  • Observer tells objects about changes in another
  • Singleton provides access to a single instance
  • Prototype polymorphic duplication of
    heterogeneous types
  • Visitor allows interaction with heterogeneous
  • 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)

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
  • Electronics must be off, including cell phones,
  • 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