52
CSE 332: Course Review Goals of this Course Review • Survey what we’ve covered so far (breadth) • Touch on key ideas in each major topic – Please make sure you’re comfortable with the details of each of these, too (depth) – More emphasis on material since midterm – But we’ll also revisit some key topics • Give you a chance to ask questions, if any – Please stop me at any time – And I’ll ask a few questions to provoke discussion

CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

Embed Size (px)

Citation preview

Page 1: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Goals of this Course Review

• Survey what we’ve covered so far (breadth)

• Touch on key ideas in each major topic– Please make sure you’re comfortable with the

details of each of these, too (depth)– More emphasis on material since midterm– But we’ll also revisit some key topics

• Give you a chance to ask questions, if any– Please stop me at any time– And I’ll ask a few questions to provoke discussion

Page 2: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Part I: Material from Before the Midterm Exam

• Material from before Midterm will make up between 1/3 and 1/2 of the Final Exam

• Make sure you understand and are comfortable with anything that you missed on the Midterm

• Please also look at the Midterm Review Slides– I’ll revisit some of the major themes, you should take a look

at the others I won’t have time for here

Page 3: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Iteration, Progress, Termination• Iteration is fundamental to loop control

– Loop is a (hopefully ;-) bounded series of steps• Iteration progresses through a range of steps

– Loop is unbounded if no progress is made• For example if someone left off the increment: ++i;

– Loop is unbounded if range does terminate• For example, if test is badly formed: while (c < 32767)

• Three main questions to answer– How does the loop’s range start– How does the loop’s range stop– How to move from one step to the next

• Many kinds of ranges– Examples include integer, exponent, logical

Page 4: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Pass By Value

void foo (){ int i = 7; baz (i);}

void baz (int j){ j = 3;}

7

7 → 3

local variable i

argument variable j (initialized with the value passed to baz, then assigned value 3)

Think of this as declaration with initialization, along the lines of:int j = what baz was passed;

Page 5: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Pass By Reference

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 thatwas passed to baz:when j is assigned 3,the passed variableis assigned 3.

7 → 3

again declarationwith initializationint & j = what baz was passed;

argument variable j

Page 6: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Execution Control and Exceptions

try { // can throw exceptions} catch (Derived &d) { // Do something} catch (Base &d) { // Do something else} catch (...) { // Catch everything else}

• Control jumps to first matching catch block

• Order matters if multiple possible matches– Especially with inheritance-

related exception classes– Put more specific catch blocks

before more general ones– Put catch blocks for more

derived exception classes before catch blocks for their respective base classes

catch(...) – catches any type

throw; – does not throw a type– essentially a call to abort()

Page 7: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Arrays of (and Pointers to) Pointersint main(int argc, char * * argv) {

for (int i = 0; i < argc; ++i) { cout << argv[i] << endl; }

return 0;}

• Can have pointers to pointers• Can also have an array of

pointers (like a const pointer to a pointer type)

• E.g., argv parameter in main– Array of pointers to character

strings– Could also declare as a

pointer to the first pointer– Array dimension is not

specified– Instead a special argument

(argc) holds array size• By convention, character strings

are zero terminated– Special char is ‘\0’ not ‘0’

0xefffbab0char * * argv

int argc 2

0xefffa0d0

h e l l ot e s t \0 \0

Page 8: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Stack vs. Dynamic Allocation• The program call stack records function calls

– Keeps a stack of “frames” – one frame per function call– Keeps values of local variables/objects in each frame– Passes parameter values/references from caller– Passes return values/references back to caller– Stack frames “pop” (and contents are destroyed) on return

• The program heap provides additional memory– Allocated “as needed” (dynamically) to a running program – Operator new obtains memory from the heap

• And returns a typed pointer to the dynamically allocated memory• May perform initialization before returning value, if value given

– Can also just initialize a given previously allocated location– Must release allocated memory with operator delete

Page 9: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Memory Management, Part II• Understand how to use new and delete operators

– Match every new with a corresponding delete– Match every new [] with a corresponding delete []– Don’t mix new with delete [] or new [] with delete– Use std::nothrow to prevent new from throwing exception

• But then you must check the return value of the call to new is != 0• Or, initialize pointer to 0, open try block, allocate, catch exception

– Dynamically allocated memory contains whatever was sitting at that location due to earlier program operations

• Use explicit allocation if you know values to use when allocating• Use “placement new” to initialize allocated memory locations

• We’ll use both stack and heap memory from now on– Especially when we talk about classes and objects

Page 10: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Class Members and Memory Locationsclass Date {

public: Date (); Date (const Date &); Date (int d, int m, int y); virtual ~Date (); operator= (const Date &); int d () const; int m () const; int y () const; void d (int); void m (int); void y (int); string yyyymmdd () const;

private: int d_, m_, y_;};

Date d

int d.d_

logical memory location

int d.m_

int d.y_

Actual memory locations

class members live in whichever memory segment an object (a class instance) was created

Page 11: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Constructors• A constructor has the same

name as its class• Establishes invariants for the

class instances (objects)– Properties that always hold– Like, no memory leaks

• Notice parameters given in base/member initialization list– Members constructed in order

they were declared• List should follow that order

– Set up invariants before the constructor body is run

– Help avoid/fix constructor failure

class Date { public: Date (); Date (const Date &); Date (int d, int m, int y); // ...private: int d_, m_, y_;};

Date::Date () : d_(0), m_(0), y_(0) {}

Date::Date (const Date &d){ : d_(d.d_), m_(d.m_), y_(d.y_) {}

Date::Date (int d, int m, int y) : d_(d), m_(m), y_(y) {}

Page 12: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Destructors• Constructors initialize objects

– At start of object’s lifetime– implicitly called when object is

created (can call explicitly)• Destructors clean up afterward

– At end of object’s lifetime– implicitly called when object is

destroyed (can call explicitly)– Compiler provides if you don’t

• Defined as member-wise destruction

• Common scenario with dynamic memory management– Constructor sets pointer to 0– Constructor or another function

allocates (calls new or new [])– If another function deallocates, sets

pointer back to 0 when appropriate– Destructor deallocates if needed

(calls delete or delete [])

class Date { public: virtual ~Date (); // ... private: int d_, m_, y_;};

Date::~Date () { // nothing to do here}

class Calendar { public: virtual ~Calendar (); // ... private: size_t size; Date * dates;};

Calendar::~Calendar () { delete [] dates;}

Page 13: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

More on Initialization and Destruction• Initialization follows a well defined order

– Base class constructor is called• That constructor recursively follows this order, too

– Member constructors are called• In order members were declared• Good style to list in that order (compiler may warn if not)

– Constructor body is run

• Destruction occurs in the reverse order– Destructor body is run– Member destructors are called– Base class destructor is called

• That destructor recursively follows this order, too

• Declare destructor as virtual (so it’s polymorphic)

Page 14: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Assignment Operator

• Compiler supplies if you don’t– Does member-wise assignment

• Similar to copy constructor– But must deal with existing value – And no initialization list

• Watch out for self-reference– Assignment to self s = s; // perfectly legal– Efficiency, correctness issues

• Watch out for aliasing/copying– Copying an int vs. an int *– Copying an int vs. an int &– Copying an int vs. an int []– More on this throughout

semester

class Date { public: operator= (const Date &); // ...private: int d_, m_, y_;};

Date::operator= (const Date &d){ d_ = d.d_; m_ = d.m_; y_ = d.y_; }

int main (int, char *[]){ Date a; // default constructor Date b(a); // copy constructor Date c = b; // copy constructor a = c; // assignment operator}

Page 15: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Static vs. Dynamic Types• Pointers have static types

– References have them too…– Type with which it was declared– Most general type it can alias

• Base is more general than Derived– Static type of bptr is Base*– Static type of dptr is Derived*

• What’s pointed to / referenced has a dynamic type– Type of object currently aliased

• Dynamic type of *bptr can be either Base or Derived

• Dynamic type of *dptr is Derived– Expands if classes inherit from Derived

– May change if pointer reassigned– May change if reference parameter

is passed a different object

class Base { public: Base (int i); Base (const Base & b); virtual ~Base (); void operator= (const Base & b); void i (int i); int i () const;private: int i_;};class Derived : public Base {public: Derived (int i, int j, int k); Derived (const Derived & d); virtual ~Derived (); void operator= (const Derived & d); void j (int j); int j () const; void k (int k); int k () const;private: int j_; int k_;}; int main (int, char *[]) { Base b (1); Derived d(2, 3, 4); Base * bptr = d; Derived * dptr = d;}

Page 16: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Virtual Destructors and the Class Slicing Problemclass A {public: A () {cout<<" A";} virtual ~A () {cout<<" ~A";}};

class B : public A {public: B () :A() {cout<<" B";} virtual ~B() {cout<<" ~B";}};

int main (int, char *[]) {

// prints "A B" A *ap = new B;

// prints "~B ~A" : would only // print "~A" if non-virtual delete ap;

return 0;};

• Derived class destructor called before base class destructor

• But, need to watch out for static versus dynamic type differences

• Making destructor virtual – ensures chain of destructor calls

starts at dynamic type and moves up– Otherwise would start at static type

(would “slice off” calls to destructors of more derived classes)

• “Class slicing problem” can also occur with pass/catch by value– Only static type gets copied– Another reason to always catch/pass

by reference (using const if needed)

Page 17: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Part II: Material Since the Midterm Exam

• Material from after Midterm will make up between 1/2 and 2/3 of the Final Exam

• (Make sure you understand and are comfortable with anything that you missed on the Midterm)

Page 18: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Overriding vs. Overloading • Signature is what distinguishes overriding from overloading

– Signature is operator/function name + ordered list of argument types– Same name, same signature means overriding

• E.g., D::add(int, long) and B::add(int, long) (same sig)

– Same name, different signature means overloading• E.g., D::add(int, long) and B::add(long, int) (different sig)

• Overriding (we covered this for virtual functions) – Same signature, but different scopes– Derived class can give its own separate definition for function/operator– If virtual, can be resolved polymorphically, using dynamic type– If non-virtual, is resolved using static type (derived class “hides” base)– Only member functions and member operators can be overridden

• Overloading– Different signatures in a common scope, declarative scopes may differ– Each overloaded operator or function must have its own definition– Can overload non-member functions and operators too!

Page 19: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Restrictions on Overloading Operators• For overloaded operators, precedence rules apply

– So, it’d be a bad idea to overload ^ to mean exponentiation– But, it’s fine to overload << for output or >> for input

• Can’t overload some of them for user-defined typessizeof (instance/type memory size) :: (scope resolution). (member selection via variable/reference).* (member selection via pointer)?: (conditional operator)typeid (Run Time Type Identification information)static_cast (all the cast operators)dynamic_castconst_castreinterpret_cast

Page 20: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Introduction to Function Templates

template <typename T>

void swap(T &lhs,

T &rhs) {

T temp = lhs;

lhs = rhs;

rhs = temp;

}

int main () {

int i = 3;

int j = 7;

swap (i,j);

return 0;

}

• Basic idea– same code is re-used for

different types

• Function template swap – takes one type parameter, T

• Definition interchanges values of two passed arguments– of the parameterized type

• Compiler infers type is really int when swap is called

• Compiler instantiates the function template definition using type int

Page 21: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Introduction to Class Templates

template <typename T>class Array {public: Array(const int size); ~Array();private: T * values_; const int size_;};

int main() { Array<int> a(10); Array<string> b(5); return 0;}

• Parameterized type T must be specified in class template declaration– Both as a parameter, and

where it’s used in the class

• When an instance is declared, must also explicitly specify the concrete type parameter– E.g., int vs. string in

function main()– In previous function template

example, didn’t have to say swap<int>

Page 22: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Inheritance vs. Concept Refinement

• Explicit inheritance relation between classes– Class2 advertises its parent, Class1

• Implicit refinement relation between concepts– Concept2 adds to the requirements of Concept1

Concept1

Concept2

T1 T2

T3 T4

refines

models

Class1

Class2

T1 T2

T3 T4

inherits from

is an instance of

Page 23: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Template Specialization

• Allows us to override behaviors– Of function templates or class templates

• Can override default (base) behavior:template <typename T> print (T t) {cout << t << endl;}

template <> print <char *> (char * str)

{cout << (void *) str << endl;}

• Partial specialization possible (some compilers)– Leave some types unspecified– While specializing on explicit types for others– E.g., on a null_guard type to remove acquire and

release overhead if no dynamic allocation is done

Page 24: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Specializations Give Polymorphismtemplate <> void print <bool>

(ostream & os, const char * message,

const bool & b) {

os << message << std::boolalpha

<< b << endl;

}

template <> void print <charptr>

(ostream & os, const char * message,

const charptr & s) {

os << message

<< reinterpret_cast<void *> (s);

if (s != 0) {

os << " (points to \""

<< s << "\")"; }

os << endl;

}

template <> void print <intptr>

(ostream & os, const char * message,

const intptr & ip) {

os << message << ip;

if (ip != 0) {

os << " (points to " << *ip << ")"; }

os << endl;

}

• Specialize on individual typesbool char * int *– Notice the use of typedef

• With specialization, we geti 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!

template <typename T>

void print (ostream & os,

const char * message,

const T & t) {

os << message << t << endl;

}

Page 25: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Container

Forward Containe

r

Reversible

Container

Random Access

Container

Sequence

Front Insertion Sequenc

e

Back Insertion Sequenc

e

General Container Concepts

refined bymodels

vector

deque

list

• 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

slist

Page 26: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Container

Simple Associative Container

Pair Associative container

Unique Associative ContainerSorted Associative Container

Multiple Associative Container

Hashed Associative Container

Associative Container Concepts

Associative

Container

Forward Container

set

multiset

map

multimap

hash_set

hash_multiset

hash_map

hash_multimap

refined bymodels

Page 27: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Overview of STL Iterators• STL iterators generalize different uses of pointers• Interface between algorithms and data structures

– Algorithm manipulates iterators, not containers• Iterator “value” can be in one of 3 kinds of states:

– Dereferenceable (points to a valid location, like in an array)– Past the end (points just past last valid location)– Singular (points to nothing, like a zero pointer)

• Iterators may be compared for equality• Iterators may be copied and assigned • The iterator family consists of five concepts:

– Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access Iterator

– We’ll look at each of these categories in detail

Page 28: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

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 [first+1, last) is also valid– Proof: iterative induction on the range

• If[first, 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

Page 29: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Iterator Concept Hierarchy

Input Iterator Output Iterator

Forward Iterator

Bidirectional Iterator

Random Access Iterator

•value persists after read/write•values have locations•can express distance between two iterators

•read or write a value (one-shot)

Linked-list style access (slist)

Bi-linked-list style access

(list)Array/buffer style access

(vector, deque)

“destructive” read at head of stream

(istream)

“transient” write to stream (ostream)

Page 30: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Advice for Designing Your Own Iterators

• Use the iterator concept requirements as a checklist• Make you support both constant and mutable objects• Define associated types appropriately

– More on this in the lecture on generic programming

• Provide as wide an iterator interface as possible without loss of efficiency

• Obey the aliasing rule we talked about with pointers– Two iterators equal if and only if they point to same variable

i == j &(*i) == &(*j)

*i == *j

Page 31: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Advice for Using Iterators• Write a concept expression checklist for iterator

developers to use in designing their iterators

• Watch out for empty ranges

• Require as narrow an iterator interface as possible without loss of efficiency– Avoid over-constraining unnecessarily

– E.g., requiring just == and < vs. also > and !=

• Use selective dispatching techniques to provide both efficiency and generality

Page 32: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Associated Types: Key Ideas to Consider

• Difference Type– Type for “distance” between

two iterators i1 and i2– E.g., ptrdiff_t

• Reference, Value Types– For T *p, value type is T, *p

normally returns T &– For const T *p, value type is

const T, *p gives const T &

• Iterator Category– What concept(s) it modelshow far? units?

how far? units?

Page 33: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Algorithm Concepts and Models

• Remember a concept gives a set of type requirements– Classify/categorize types (e.g., random access iterators)– Tells whether or not a type can or cannot be used with a

particular STL algorithm (get a compiler error if it cannot)• E.g., we couldn’t use a linked list iterator in find1 or even find2

• Any specific type that meets the requirements is a model of that concept– E.g., list<int>::iterator vs. char * in find

• Different abstractions (bi-linked list vs. array iterators)• No inheritance-based relationship between them • But both model iterator concept necessary for find

Page 34: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Concepts and Modeling, Continued• What very basic concept does the last statement in

STL find, (the line return first;) assume?– Asked another way, what must be able to happen to first

when it’s returned from function find? – Same requirement imposed by by-value iterator parameters

• What other capabilities are required of the Iterator and T type parameters by the STL find algorithm ?

template <typename Iterator, typename T>Iterator find (Iterator first, Iterator last,

const T & value) { while (first != last && *first != value) ++first; return first;}

Page 35: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Matching an Algorithm to the Iterators it Needs

Category Output Input Forward BidirectionalRandom

Access

Read =*p =*p =*p =*p

Access -> -> ->->

[]

Write *p= *p= *p= *p=

Iteration ++ ++ ++ ++ --++ -- + - += -=

Comparison == != == != == !=== != < > <= >=

What STL iterator category does find require?

Page 36: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Examples of Function Object Usagestruct GT_magnitude : public

binary_function<double, double, bool> { bool operator() (double x, double y) {

return fabs(y) < fabs(x); }};struct LT_magnitude : public

binary_function<double, double, bool> { bool operator() (double x, double y) {

return fabs(x) < fabs(y); }};

int main (int, char **) {

vector<double> u,v;

for (double d = 0.0;

d < 10.1; d += 1.0){

u.push_back (d);

v.push_back (d);

}

sort (u.begin(), u.end(),

GT_magnitude());

sort (v.begin(), v.end(),

LT_magnitude());

ostream_iterator<double>

o (cout, “ ”));

copy (u.begin(), u.end(), o);

copy (v.begin(), v.end(), o);

return 0;

}

Page 37: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Function Object Concepts• Basic Function Object Concepts

– Generator– Unary Function– Binary Function

• Adaptable Function Objects (turn functions into functors)– Adaptable Generator– Adaptable Unary Function– Adaptable Binary Function

• Predicates (return a boolean result)– Predicate– Binary Predicate– Adaptable Predicate– Adaptable Binary Predicate– Strict Weak Ordering

• Specialized Concepts– Random Number Generator– Hash Function

Page 38: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Function Object Concept Hierarchy

Adaptable Function Object

Basic Function Object

Specialized

Predicate

is-refined-byGenerator

UnaryFunction

BinaryFunction

Assignable

AdaptableGenerator

AdaptableUnary

Function

AdaptableBinary

Function

HashFunction

RandomNumber

GeneratorPredicate

AdaptablePredicate

BinaryPredicate

AdaptableBinary

Predicate

StrictWeak

Ordering

Page 39: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Type Programming Techniques in C++

• Associated types– Let you associate a type with another type– Given one type, let you obtain another type– Let you control encapsulation of type information

• Typedefs– Let you give a known type another name– Let you name associated types consistently

• Across various user-defined/built-in/const/non-const types

• Traits– Let you associate user-defined and built-in types– Let you provide consistent access across types

Page 40: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Partial Specialization of Iterator Traits

• Fourth approach: a complete solution– Use partial specialization of a

general traits struct template• Still have to parameterize struct iterator_traits with typename I

• Can’t do full specialization since we’re using type parameter T

– Gives us different versions of the iterator_traits struct

• For user-defined, built-in types• For const, non-const types

– C++ compiler will select the most specific match

// Based on Austern, pp. 35

template <typename I>

struct iterator_traits {

typedef typename I::value_type

value_type;

};

template <typename T>

struct iterator_traits<T*> {

typedef T value_type;

};

template <typename T>

struct iterator_traits<const T*>

{

typedef T value_type;

};

Page 41: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Declaring Your Own Traits• Could have used

pointer traits already provided by the STL– But, it’s good to see the

technique itself again• So you can associate

other types as needed– Notice use of partial

specialization and use of typename, again

– Notice separate partial specializations for const and non-const, again

• Now we have our associated types– Can use in an even

more generic print function template

template <typename T>struct print_traits { typedef typename T::value_type value_type;};

// partial specialization for pointerstemplate <typename T> struct print_traits<T *> { typedef T value_type;};

// partial specialization for const pointerstemplate <typename T> struct print_traits<const T *> { typedef T value_type;};

Page 42: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Using Traits in a Generic Function Template

• Generic print function template– Takes iterator type parameter– Takes iterators as function

parameters (define a range)• Used typedef for convenience

– Here, as a kind of local type name declaration

– Avoid excessive use, but can aid coding style in some cases

• Applies generically to iterators– Including const and non-const

pointers to memory locations

#include "print_T.h"#include <iterator>#include <algorithm>

using namespace std;

template <typename I>void print (I i, I j) {

typedef typename print_traits<I>::value_type VTYPE;

ostream_iterator<VTYPE> osi (cout, " ");

copy (i, j, osi); cout << endl;}

Page 43: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

New Idea: Associated Type for Iterator Category• Output iterator

typename iterator_traits<x>::iterator_category

• Input, forward, bidirectional, and random access iterators typename iterator_traits<x>::iterator_category

typename iterator_traits<x>::value_type

typename iterator_traits<x>::difference_type

typename iterator_traits<x>::pointer

typename iterator_traits<x>::reference

• Iterator category types: empty structs for type tags (note use of inheritance)struct output_iterator_tag {};

struct input_iterator_tag {};

struct forward_iterator_tag : public input_iterator_tag {};

struct bidirectional_iterator_tag :

public forward_iterator_tag {};

struct random_iterator_tag :

public bidirectional_iterator_tag {};

Page 44: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Dispatching Algorithms using Iterator Tags• A better approach:

static dispatch– Different signatures

of implementations (allows overloading)

– Compile-time iterator type test based on iterator category tags

– Can use traits to give tags to pointers

– Links to the best implementation

// Based on Austern, pp. 38, 39

template <class Iter, class Distance>

void move (Iter i, Distance d,

forward_iterator_tag) {

while (d>0) {--d; ++i} // O(d)

}

template <class Iter, class Distance>

void move (Iter i, Distance d,

random_iterator_tag) {

i+=d; // O(1)

}

template <class Iter, class Distance>

void move (Iter i, Distance d) {

move (i, d,

iterator_traits<Iter>::

iterator_category());

}

tag (empty class) type

explicit constructor call

Page 45: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

copy Algorithm (Input vs. Random Access)

• First version of copy compares iterators

• Second version of copy compares distance

• No performance improvement in number of assignments made

• but each comparison may be faster

template<typename _InputIter, typename _OutputIter>inline _OutputIter__copy (_InputIter __first, _InputIter __last,

_OutputIter __result, input_iterator_tag) { for ( ; __first != __last; ++__result, ++__first) *__result = *__first; return __result;}

template<typename _RandomAccessIter, typename _OutputIter>inline _OutputIter__copy (_RandomAccessIter __first, _RandomAccessIter __last,

_OutputIter __result, random_access_iterator_tag) { typedef typename iterator_traits<_RandomAccessIter>::difference_type _Distance;

for (_Distance __n = __last - __first; __n > 0; --__n) { *__result = *__first; ++__first; ++__result; }

return __result;}

Page 46: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

“Gang of Four” Design Pattern Structure

• Gang of Four (GoF): Gamma, Johnson, Helm, Vlissides– Authors of the popular “Design Patterns” book

• A pattern has a name– e.g., the Command pattern

• A pattern documents a recurring problem– e.g., Issuing requests to objects without knowing in advance what’s

to be requested or of what object

• A pattern describes the core of a solution– e.g., class roles, relationships, and interactions– Important: this is different than describing a design

• A pattern considers consequences of its use– Trade-offs, unresolved forces, other patterns to use

Page 47: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

A More Complete Pattern Form: “Command”• Problem

– Want to issue requests to objects– Don’t know in advance which request(s) will be made– Don’t know in advance to what object(s) they will go

• Solution core– Encapsulate function call parameters and target object

reference inside an “execute” method

• Consequences– Decouples invocation/execution – Commands are first-class objects (elevates functions)– Easy to compose, add new ones

• Example we’ve seen already– STL function objects

Page 48: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Structure Diagram Example: “Command”

• Shows fixed class/interface roles in the pattern• Shows fixed relationships between roles

<<Client>>

<<ConcreteCommand>>

<<Command>><<Invoker>>

<<Receiver>>

action(args)

execute ( )

execute ( )

state_

*

client role command role

inheritance

Page 49: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Collaboration Diagram Example: “Command”• Shows dynamic interactions between pattern roles

– Labels show what interaction does (here, labels show methods called)

• Often used to diagram each of several key scenarios– “Happy path” when everything works, plus different error cases

aCommand anInvokeraClient aReceiver

/ // / / / / /

construct

store

executeaction

time

Page 50: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Idiom Example: Guard

• Problem– Want to tie key scoped behaviors to actual program scopes

• e.g., program trace, resource acquisition/release, locking

– However, tying functions to functions is error-prone• e.g., forgetting the release call, exceptional return paths

• Solution– Design a special adapter class whose constructor and

destructor call the key scope entry and exit behaviors – Create a guard object on the program call stack (in a scope)

• Context limitations– Mainly limited to languages with constructor/destructor

Page 51: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Design Patterns Summary• We’ve looked at quite a few patterns

– Singleton: share a class instance across multiple uses– Command: package up a function as an object– Iterator: access elements sequentially no matter how stored– Adapter: converts interface you get into one you want– Factory method: creates a related type polymorphically– Bridge: allow interface, implementation to vary separately– Chain of responsibility: give request to chain of handlers– Composite: common interface to composite/simple objects– Interpreter: build a representation for a simple language– Observer: tell registered observers when state changes– Strategy/template method: vary steps/all of an algorithm– Proxy: forward requests from placeholder to another object– Memento: package up object state without violating encapsulation– Visitor: allow various operations on fixed set of objects (2-way dispatch)

• Think of these as a “design vocabulary” that you can use• CSE 432 will use these throughout next semester

– In iterative refinement of project designs and implementations

Page 52: CSE 332: Course Review Goals of this Course Review Survey what we’ve covered so far (breadth) Touch on key ideas in each major topic –Please make sure

CSE 332: Course Review

Final Exam

• 8-10am Wednesday, December 21st

– In the lecture hall, Whitaker 218– 120 minutes, starting promptly at 8am – Two 8.5” x 11” pages allowed (both sides ok)– Please bring a few pens and/or pencils– Exam is otherwise closed

• no books, other notes, PDAs, cell phones, etc.

• Alternate final exam time and location– Monday December 19th, 10am-noon, Bryan 509C– You must ask in advance if you want to take the final then