10-1 computing fundamentals with c++ object-oriented programming and design, 2nd edition rick mercer...

47
10-1 Computing Fundamentals Computing Fundamentals with C++ with C++ Object-Oriented Programming and Design, Object-Oriented Programming and Design, 2nd Edition 2nd Edition Rick Mercer Rick Mercer Franklin, Beedle & Associates, 1999 Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8 ISBN 1-887902-36-8 Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Students who purchase and instructors who adopt Computing Computing Fundamentals with C++, Object-Oriented Programming and Design Fundamentals with C++, Object-Oriented Programming and Design by Rick Mercer by Rick Mercer are welcome to use this presentation as long as this copyright are welcome to use this presentation as long as this copyright notice remains intact. notice remains intact.

Upload: nora-lawrence

Post on 17-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-1

Computing Fundamentals with C++Computing Fundamentals with C++Object-Oriented Programming and Design, 2nd EditionObject-Oriented Programming and Design, 2nd Edition

Rick MercerRick Mercer

Franklin, Beedle & Associates, 1999Franklin, Beedle & Associates, 1999

ISBN 1-887902-36-8ISBN 1-887902-36-8

Presentation Copyright 1999, Franklin, Beedle & Associates Presentation Copyright 1999, Franklin, Beedle & Associates Students who purchase and instructors who adopt Students who purchase and instructors who adopt Computing Fundamentals with C++, Computing Fundamentals with C++, Object-Oriented Programming and Design Object-Oriented Programming and Design by Rick Mercer are welcome to use this by Rick Mercer are welcome to use this

presentation as long as this copyright notice remains intact.presentation as long as this copyright notice remains intact.

Page 2: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-2Chapter 10Chapter 10VectorsVectors

Chapter ObjectivesChapter Objectives Construct vector objects that can store collections of Construct vector objects that can store collections of

like objects like objects e.g. one vector can store many numbers e.g. one vector can store many numbers

Implement algorithms to process a collection of Implement algorithms to process a collection of objects objects e.g. display all elements, find min/maxe.g. display all elements, find min/max

Use the sequential search algorithm to locate a Use the sequential search algorithm to locate a specific element in a vectorspecific element in a vector

Pass vector objects to functionsPass vector objects to functions– ExercisesExercises– Programming ProjectsProgramming Projects

Page 3: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-3 Second Part of Chapter 10Second Part of Chapter 10

Part IIPart II Sort vector elements into ascending or Sort vector elements into ascending or

descending orderdescending order Understand the binary search algorithm.Understand the binary search algorithm. Implement a container class with a vector data Implement a container class with a vector data

member member PREREQUISITE: Chapter 6PREREQUISITE: Chapter 6

– ExercisesExercises

– Programming ProjectsProgramming Projects

– Note: There are two sets of exercises and programming Note: There are two sets of exercises and programming projectsprojects

Page 4: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-4

Some objects store precisely one value:Some objects store precisely one value: a double store one numbera double store one number an int stores one integer an int stores one integer

Other objects store more than one (possibly Other objects store more than one (possibly dissimilar) values, for example:dissimilar) values, for example:

bankAccount objects store a string and a doublebankAccount objects store a string and a double

What does a string object store?What does a string object store? not surenot sure

10.1 The Standard C++ 10.1 The Standard C++ vector Classvector Class

Page 5: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-5 Recall string objects Recall string objects

Any string object stores a collection of Any string object stores a collection of characters (more than one value)characters (more than one value)

individual characters are referenced with [ ]individual characters are referenced with [ ]cout << myName[0]; cout << myName[0]; // reference the 1st char// reference the 1st char

This chapter introduces vector objects whichThis chapter introduces vector objects which stores a collection of similar objects.stores a collection of similar objects. Individual objects are accessed through Individual objects are accessed through

subscriptssubscripts[][]

Page 6: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-6 vectors are genericvectors are generic

This code declares a vector named This code declares a vector named xx vector <double> x( 100, 0.0 );vector <double> x( 100, 0.0 ); x[0] = 90.5;x[0] = 90.5; x[1] = 77.34;x[1] = 77.34;

that has the capacity to store 100 numbersthat has the capacity to store 100 numbers the first two elements store 90.5 and 77.34the first two elements store 90.5 and 77.34 the other 98 elements are 0.0 the other 98 elements are 0.0 the 2nd constructor argumentthe 2nd constructor argument

We can have a vector of almost any class of We can have a vector of almost any class of objects objects the default constructor is used herethe default constructor is used here

vector <almostAnyClass> x( 100 );vector <almostAnyClass> x( 100 );

Page 7: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-7 vectors are...vectors are...

A vector is A vector is homogeneous homogeneous because all objects because all objects stored under one vector name must be of the stored under one vector name must be of the same classsame class

vectors may be sized (at compile-time) or vectors may be sized (at compile-time) or dynamically sized (at runtime)dynamically sized (at runtime)

we can set the capacity of a vector at runtimewe can set the capacity of a vector at runtime cout << "Number of students?";cout << "Number of students?"; cin >> n;cin >> n; vector <student> university(n); vector <student> university(n); // default constructor called for n elements// default constructor called for n elements

Page 8: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-8General form of vector General form of vector constructionconstruction

vectorvector <<classclass>> identifier identifier ( ( capacitycapacity, , initial-value initial-value ) ;) ; classclass specifies the class of objects stored in the vector specifies the class of objects stored in the vector

object object identifier identifier is the name of the vector objectis the name of the vector object capacity capacity is an integer expression specifying the is an integer expression specifying the

maximum number of objects that can be storedmaximum number of objects that can be stored initial-valueinitial-value is the value that every element will be set is the value that every element will be set

to. The to. The initial valueinitial value is optional is optional If the initial-value is omitted, the default constructor If the initial-value is omitted, the default constructor

initializes every object in the vector initializes every object in the vector – Suggestion: if Suggestion: if classclass is is intint or or doubledouble, specify an , specify an initial-valueinitial-value

Page 9: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-9 Example ConstructionsExample Constructions

A vector that stores up to 8 numbers, which are all A vector that stores up to 8 numbers, which are all initialized to 0.0 initialized to 0.0

vector <double> x(8, 0.0); vector <double> x(8, 0.0);

A vector that stores 500 string objects:A vector that stores 500 string objects: vector <string> name(500);vector <string> name(500);

A vector that store 1,000 integers, which are all A vector that store 1,000 integers, which are all initialized to -1):initialized to -1):

vector <int> test(1000, -1);vector <int> test(1000, -1);

A vector that stores up to 100 bankAccounts A vector that stores up to 100 bankAccounts vector <bankAccount> customer(100); vector <bankAccount> customer(100);

Page 10: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-1010.1.1 Accessing Individual 10.1.1 Accessing Individual Elements in the CollectionElements in the Collection

Individual array elements are referenced through Individual array elements are referenced through subscripts of this form:subscripts of this form:

vector-name vector-name [[ int-expressionint-expression ]] int-expressionint-expression is an integer that should be in the is an integer that should be in the

range of 0..range of 0..capacitycapacity-1.-1.

Examples:Examples: x[0] x[0] // Pronounced// Pronounced x sub 0x sub 0 name[5] name[5] // Pronounced // Pronounced name sub 5name sub 5 test[99] test[99] // Pronounced // Pronounced test sub 99test sub 99 customer[12] customer[12] // Pronounced // Pronounced customer sub 12customer sub 12

Page 11: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-11Assignment and input operations Assignment and input operations work on individual vector elementswork on individual vector elements

#include <vector> #include <vector> // for the standard vector class// for the standard vector class#include <iostream>#include <iostream>using namespace std;using namespace std;int main() {int main() { int n = 5;int n = 5; vector <int> x(n, 0);vector <int> x(n, 0); x[0] = 1;x[0] = 1; // Assume input of// Assume input of cout << "Enter two integers: "; cout << "Enter two integers: "; //// 2 5 2 5 cin >> x[1] >> x[2];cin >> x[1] >> x[2]; x[3] = x[0] + x[2];x[3] = x[0] + x[2]; x[4] = x[3] - 1;x[4] = x[3] - 1; for(int j = 0; j < n; j++) for(int j = 0; j < n; j++) // LOOP OUTPUT?// LOOP OUTPUT? { { cout << x[j] << endl;cout << x[j] << endl; }} return 0;return 0;}}

Page 12: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-12The vector after modifying its The vector after modifying its statestate

Page 13: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-1310.1.2 Vector Processing with 10.1.2 Vector Processing with Determinate for LoopsDeterminate for Loops

The need often arises to access all meaningful The need often arises to access all meaningful elements elements e.g.e.g. sum the first n elements in testsum the first n elements in test

vector <double> test(100, -99.9);vector <double> test(100, -99.9); test[0] = 64; test[0] = 64; test[1] = 82;test[1] = 82; // … assume 21 additional assignments … // … assume 21 additional assignments … test[23] = 97;test[23] = 97; int n = 24;int n = 24; double sum = 0.0;double sum = 0.0; for(int j = 0; j < n; j++)for(int j = 0; j < n; j++) {{ sum += test[j];sum += test[j]; }}

Page 14: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-1410.1.3 Processing the First 10.1.3 Processing the First nn Elements of a vectorElements of a vector

A vector often has capacity larger than need beA vector often has capacity larger than need be The previous example only used the first 24 of a The previous example only used the first 24 of a

potential 100 elements.potential 100 elements. The textbook often uses The textbook often uses nn to represent the number of to represent the number of

initialized and meaningful elementsinitialized and meaningful elements The previous loop did not add The previous loop did not add x[24]x[24] nor nor x[25]x[25], nor , nor x[99]x[99] all of which were -99.9all of which were -99.9

vectors can be sized at runtime vectors can be sized at runtime and even resized laterand even resized later

Page 15: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-15vector processing in this text vector processing in this text bookbook

Example vector processing you will seeExample vector processing you will see displaying some or all vector elements displaying some or all vector elements finding the sum, or average, or highest of all vector finding the sum, or average, or highest of all vector

elementselements searching for a given value in the vectorsearching for a given value in the vector arranging elements in a certain order arranging elements in a certain order

ordering elements from largest to smallestordering elements from largest to smallest or alphabetizing a vector of strings from smallest to or alphabetizing a vector of strings from smallest to

largestlargest

Page 16: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-1610.1.4 Out of Range 10.1.4 Out of Range Subscript Checking Subscript Checking

Most vector classes don't care if you use Most vector classes don't care if you use subscripts that are out of rangesubscripts that are out of range

vector <string> name(1000);vector <string> name(1000); name[-1] = "Subscript too low";name[-1] = "Subscript too low"; name[ 0] = "This should be the first name";name[ 0] = "This should be the first name"; name[999] = "This is the last good subscript";name[999] = "This is the last good subscript"; name[1000] = "Subscript too high";name[1000] = "Subscript too high";

These other vector classes let you crash your These other vector classes let you crash your computer instead! computer instead! segmentation or general protection faultssegmentation or general protection faults

Page 17: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-17With MSVC++ 5.0 in With MSVC++ 5.0 in Windows 95Windows 95

The standard vector class distributed with this The standard vector class distributed with this Microsoft's Compiler also gracefully terminates Microsoft's Compiler also gracefully terminates the program with this:the program with this:

Page 18: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-18 Range CheckingRange Checking

Optional Demo: rangerr.cpp

See if you can get the safe vector

Recommendation: use the vector class from this Recommendation: use the vector class from this textbooks disktextbooks disk

copy vector into your working foldercopy vector into your working folder including it this way works on Unix systems:including it this way works on Unix systems:

#include "vector" #include "vector" // for a safe vector class// for a safe vector class

Or you could change your include path settings to Or you could change your include path settings to search the current folder first and then write thissearch the current folder first and then write this

#include <vector> #include <vector> // for a safe vector class// for a safe vector class

Page 19: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-1910.1.5 vector::capacity and 10.1.5 vector::capacity and vector::resizevector::resize

The proper capacity of a vector is usually an The proper capacity of a vector is usually an issueissue

There are two useful functions to help There are two useful functions to help int vector::capacity()int vector::capacity()

void vector::resize(int newSize)void vector::resize(int newSize)

Page 20: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-20vector::capacity and vector::capacity and vector::resizevector::resize

#include <vector> #include <vector> // for the standard vector class // for the standard vector class using namespace std;using namespace std;int main()int main(){{ vector <int> v1; vector <int> v1; // v1 cannot store any elements// v1 cannot store any elements vector <int> v2(5);vector <int> v2(5);

cout << "v1 can hold " << v1.capacity() << endl;cout << "v1 can hold " << v1.capacity() << endl; cout << "v2 can hold " << v2.capacity() << endl;cout << "v2 can hold " << v2.capacity() << endl;

v1.resize(22);v1.resize(22); cout << "v1 can now hold " << v1.capacity() << endl;cout << "v1 can now hold " << v1.capacity() << endl;

return 0;return 0;}}

Output:Output:v1 can hold 0v1 can hold 0v2 can hold 5v2 can hold 5v1 can now hold 22v1 can now hold 22

Page 21: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-21What happens during a resize What happens during a resize message?message?

When a vector is resized When a vector is resized this book's safe vectorthis book's safe vector

and the new size is bigger than the old sizeand the new size is bigger than the old size the existing elements are intactthe existing elements are intact

and the new size is smaller than the old sizeand the new size is smaller than the old size the elements in the highest locations are truncatedthe elements in the highest locations are truncated

Page 22: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-22 10.2 Sequential Search10.2 Sequential Search

We often need to search for data stored in a We often need to search for data stored in a vector (a phone number, an inventory item, an vector (a phone number, an inventory item, an airline reservation, a bank customer) airline reservation, a bank customer)

We will simplify the search algorithm by We will simplify the search algorithm by searching only for stringssearching only for strings

Imagine however that the vector may be a Imagine however that the vector may be a collection of bankAccounts, students, inventory, collection of bankAccounts, students, inventory, sales, employees, or reservations sales, employees, or reservations

Page 23: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-23 Sequential search algorithmSequential search algorithm

There are many searching algorithmsThere are many searching algorithms We will study the We will study the sequential searchsequential search algorithm algorithm

with a simple collection of stringswith a simple collection of strings Here is the first cut at the algorithm:Here is the first cut at the algorithm:

Initialize a vector of strings (call it myFriends)Initialize a vector of strings (call it myFriends)

Get the name to search for (call it searchName)Get the name to search for (call it searchName)

Try to find searchNameTry to find searchName

Report on success or failure of searchReport on success or failure of search

Page 24: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-24 The array being searchedThe array being searched

We'll use this data in our searches:We'll use this data in our searches: vector <string> myFriends(10);vector <string> myFriends(10); int n = 5;int n = 5; myFriends[0] = "DEBBIE";myFriends[0] = "DEBBIE"; myFriends[1] = "JOEY";myFriends[1] = "JOEY"; myFriends[2] = "BOBBIE";myFriends[2] = "BOBBIE"; myFriends[3] = "SUSIE";myFriends[3] = "SUSIE"; myFriends[4] = "MIKEY";myFriends[4] = "MIKEY";

Note: We often have unused elements in a Note: We often have unused elements in a vector. For example, we could add 5 more vector. For example, we could add 5 more strings to the collection named strings to the collection named myFriendsmyFriends..

Page 25: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-25 The Possibilities?The Possibilities?

searchName is in the vectorsearchName is in the vector searchName is searchName is notnot in the vector in the vector Now: write the code that stores the index Now: write the code that stores the index

(subscript) of(subscript) of searchNamesearchName in in myFriendsmyFriends

string searchName;string searchName; cout << "Enter name to search for: ";cout << "Enter name to search for: "; cin >> searchName;cin >> searchName;DialogueDialogue Enter name to search for: Enter name to search for: BOBBIEBOBBIE

Page 26: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-26 Sequential SearchSequential Search

// assert: searchName is in myFriends// --if it is not, watch out!

// Search for searchName starting at myFriends[0]

int subscript = 0; while(searchName != myFriends[subscript]) { // assert: searchName has not yet been found subscript++; // compare to next vector element}

Page 27: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-27 Example search for Example search for "BOBBIE""BOBBIE"

Example Search: "BOBBIE"

LoopIteration searchName n

Looptest subscript

Vectorelement

before "BOBBIE" 5 NA 0 N/A#1 " " true 0 "DEBBIE"#2 " " " 1 "JOEY"#3 " " false 2 "BOBBIE"

after loop " " " " N/A

Page 28: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-28 Report success or failureReport success or failure

// Report success or failure (see changes below)

if(subscript < n) cout << myFriends[subscript] << " found";else cout << searchName << " not found";

Question: What would happen if searchName Question: What would happen if searchName was not amongst myFriends ?was not amongst myFriends ?

Page 29: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-29What if searchName isn't there?What if searchName isn't there?

LoopIteration searchName n

LoopTest subscript

Vectorelement

before "SOMEONE" 5 true 0 N/A

#1 " " true 0 "DEBBIE"

#2 " " true 1 "JOEY"

#3 " " true 2 "BOBBIE"

#4 " " true 3 "SUSIE"

#5 " " true 4 "MIKEY"

#6 " " true 5 ""

#7 " " true 6 ""

#8 " " true 7 ""

#9 " " true 8 ""

#10 " " true 9 ""

#11 ? " " maybe 10 no more#12 ? " " maybe 11 ...

Page 30: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-30 Active LearningActive Learning

Rewrite the sequential search algorithm so it Rewrite the sequential search algorithm so it works even if works even if searchNamesearchName is not in the vector is not in the vector myFriendsmyFriends

int subscript = 0;int subscript = 0;

while( while( ________________________________________________________

________________________________________________________ ) ) {{ subscript++;subscript++; }}

Page 31: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-3110.3 Messages to individual 10.3 Messages to individual objects in a vectorobjects in a vector

General form for sending a message to an General form for sending a message to an individual object in a vector:individual object in a vector:

vector-name vector-name [[ subscriptsubscript ]] .. messagemessage Examples:Examples:

vector <string> name(1000);vector <string> name(1000); vector <bankAccount> acct(10000);vector <bankAccount> acct(10000); name[3] = "Any string";name[3] = "Any string"; int n( name[3].length() );int n( name[3].length() ); acct[99] = bankAccount("Westphall", 345.67); acct[99] = bankAccount("Westphall", 345.67); acct[99].withdraw(100.00);acct[99].withdraw(100.00); cout << acct[99].balance() << endl; cout << acct[99].balance() << endl;

Page 32: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-3210.3.1 Initializing a vector of 10.3.1 Initializing a vector of Objects with File InputObjects with File Input

A vector is often initialized with file inputA vector is often initialized with file input For example, might need to initialize a data For example, might need to initialize a data

base of bank customers with this file input:base of bank customers with this file input: Cust0 0.00Cust0 0.00 AnyName 111.11AnyName 111.11 Austen 222.22 Austen 222.22 Chelsea 333.33Chelsea 333.33 Kieran 444.44Kieran 444.44 Cust5 555.55Cust5 555.55 ... Note: Seven lines are omitted ... ... Note: Seven lines are omitted ... Cust11 1111.11Cust11 1111.11

Page 33: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-33 Some preliminariesSome preliminaries

// Initialize a vector of bankAccounts through file input// Initialize a vector of bankAccounts through file input #include <fstream> #include <fstream> // for class ifstream// for class ifstream #include <iostream>#include <iostream> // for cout // for cout #include <vector> #include <vector> // for the standard vector class// for the standard vector class #include "baccount" #include "baccount" // for class bankAccount// for class bankAccount

int main() int main() {{ ifstream inFile( "bank.dat" );ifstream inFile( "bank.dat" ); if( ! inFile )if( ! inFile ) {{ cout << "*Error* file 'bank.dat' not found" << endl; cout << "*Error* file 'bank.dat' not found" << endl; }} elseelse {{

Page 34: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-34 Reading until end of fileReading until end of file

vector <bankAccount> account( 20 );vector <bankAccount> account( 20 ); string name;string name; double balance = 0.0;double balance = 0.0; int n = 0;int n = 0; int j = 0;int j = 0;

while( ( inFile >> name >> balance ) while( ( inFile >> name >> balance ) && ( n < account.capacity() ) )&& ( n < account.capacity() ) ) {{ // Create and store a new bankAccount in next location// Create and store a new bankAccount in next location account[ n ] = bankAccount( name, balance );account[ n ] = bankAccount( name, balance ); // Increase initialized accounts and// Increase initialized accounts and // get ready to locate the next new bankAccount // get ready to locate the next new bankAccount n++;n++; }}} } // end else// end else

Optional Demo: file2vec.cpp

Page 35: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-3510.4 vector Argument/Parameter 10.4 vector Argument/Parameter Associations Associations by exampleby example

void foo( vector < bankAccount > acct )void foo( vector < bankAccount > acct ) { { // // VALUEVALUE parameter parameter (should not be used with vectors)(should not be used with vectors)

// all elements of acct are copied // all elements of acct are copied // after allocating the additional memory// after allocating the additional memory }}

void foo( vector < bankAccount > void foo( vector < bankAccount > && acct ) acct ) { { // // REFERENCEREFERENCE parameter ( parameter (allows changes to argument)allows changes to argument)

// Only a pointer the acct is copied. // Only a pointer the acct is copied. // A change to acct changes the argument// A change to acct changes the argument }} void foo( void foo( constconst vector<bankAccount> vector<bankAccount> && acct ) acct ) { { // // CONST REFERENCECONST REFERENCE parameter parameter (for efficiency and safety)(for efficiency and safety)

// Only a reference to the acct is copied (4 bytes) // Only a reference to the acct is copied (4 bytes) // A change to acct does NOT change the argument// A change to acct does NOT change the argument }}

Page 36: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-36Example vector pass vector by Example vector pass vector by referencereference

void init(vector < int > & x, int & n){ n = 4; x.resize(n); x[0] = 0; x[1] = 11; x[2] = 22; x[3] = 33; }

int main(){ vector <int> test; int n = 0; init(test, n); // aVector has a capacity of 4

Page 37: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-37 10.5 Sorting 10.5 Sorting

Sorting:Sorting: the process of arranging vector elements into the process of arranging vector elements into ascending or descending order: ascending or descending order:

Ascending (where x is a vector object):Ascending (where x is a vector object): x[0] <= x[1] <= x[2] <= ... <= x[n-2] <= x[n-1] x[0] <= x[1] <= x[2] <= ... <= x[n-2] <= x[n-1]

Descending:Descending: x[0] >= x[1] >= x[2] >= ... >= x[n-2] >= x[n-1]x[0] >= x[1] >= x[2] >= ... >= x[n-2] >= x[n-1]

Here's the data used in the next few slides:Here's the data used in the next few slides:

Object Unsorted Sortedtest[0] 76 100test[1] 74 89test[2] 100 76test[3] 62 74test[4] 89 62

Page 38: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-38 Swap largest with the firstSwap largest with the first

// Swap the largest element with the first// Swap the largest element with the firsttop = 0top = 0largestIndex = toplargestIndex = topfor j ranging from top+1 through n - 1for j ranging from top+1 through n - 1{{ if test[ j ] > test[ largestIndex ] thenif test[ j ] > test[ largestIndex ] then largestIndex = j largestIndex = j }}// Question: What is largestIndex now __________?// Question: What is largestIndex now __________?swap test[ largestIndex ] with test[ top ]swap test[ largestIndex ] with test[ top ]

Page 39: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-39 Selection sort algorithmSelection sort algorithm

Now we can sort the entire vector by changing Now we can sort the entire vector by changing top from 0 to n-2 with this looptop from 0 to n-2 with this loop

for (top = 0; top < n-1; top++)for (top = 0; top < n-1; top++)

for each subvector, get the largest on topfor each subvector, get the largest on top

The top moves down one vector position each The top moves down one vector position each time the largest is placed on toptime the largest is placed on top

Eventually, we get a sorted vector Eventually, we get a sorted vector

Page 40: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-40 Trace selection sortTrace selection sort

Optional Demo: Optional Demo: sort.cpp sort.cpp

(n=5) UnsortedArray

PartiallySortedArraytop = 0

PartiallySortedArraytop = 1

PartiallySortedArraytop = 2

SortedArraytop = 3

test[0] 76 ? ? ? ?test[1] 74 ? ? ? ?test[2] 100 ? ? ? ?test[3] 62 ? ? ? ?test[4] 89 ? ? ? ?

Page 41: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-41 10.6 Binary Search10.6 Binary Search

We'll see that binary search can be a more We'll see that binary search can be a more efficient algorithm for searchingefficient algorithm for searching

It works only on sorted arrays like thisIt works only on sorted arrays like this Compare the element in the middleCompare the element in the middle if that's the target, quit and report successif that's the target, quit and report success if the key is smaller, search the array to the leftif the key is smaller, search the array to the left otherwise search the array to the rightotherwise search the array to the right

This process repeats until we find the target or This process repeats until we find the target or there is nothing left to searchthere is nothing left to search

Page 42: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-42

Binary Search HarryBinary Search Harry

Bob

Carl

Froggie

Gene

Harry

Igor

Debbie

Evan

a[0]

a[1]

a[2]

a[3]

a[4]

a[5]

a[6]

a[7]

a[8]

low

mid

high

low

mid

highJudy

Data reference pass 1 pass 2

Page 43: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-43 How fast is Binary Search?How fast is Binary Search?

Best case: 1 comparisonBest case: 1 comparison Worst case: when the target is not thereWorst case: when the target is not there At each pass, the live portion of the array (where we At each pass, the live portion of the array (where we

need to search) is narrowed to half the previous sizeneed to search) is narrowed to half the previous size The series proceeds like this:The series proceeds like this:

n , n/2, n/4, n/8, ...n , n/2, n/4, n/8, ... Each term in the series represents one comparison Each term in the series represents one comparison

How long does it take to get to 1?How long does it take to get to 1? This will be the number of comparisonsThis will be the number of comparisons

Page 44: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-44 Comparing O(n) sequential search Comparing O(n) sequential search to O(log n) binary searchto O(log n) binary search

Power of 2 n log2n

24

16 4

28

128 8

212

4,096 12

224

16,777,216 24

Rates of growth and logarithmic functions

Page 45: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-45 Graph Illustrating Relative GrowthGraph Illustrating Relative Growth

n

f(n)

n

log n

Page 46: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-46 Defective Binary SearchDefective Binary Search

Binary search sounds simple, but it's tricky Binary search sounds simple, but it's tricky consider this codeconsider this code int binarySearch(const vector <int> & a, int binarySearch(const vector <int> & a, int n, int target)int n, int target) { { // pre: array a is sorted from a[0] to a[n-1]// pre: array a is sorted from a[0] to a[n-1] int first = 0, last = n-1, int mid;int first = 0, last = n-1, int mid; while(first <= last) while(first <= last) {{ mid = (first+last)/2;mid = (first+last)/2; if(target == a[mid])if(target == a[mid]) return mid; return mid; // found target// found target else if(target < a[mid])else if(target < a[mid]) last = mid; last = mid; // must be that target > a[mid]// must be that target > a[mid] else else first = mid; first = mid; // must be that target > a[mid]// must be that target > a[mid] }} return -1; return -1; // use -1 to indicate item not found // use -1 to indicate item not found }}

Page 47: 10-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN 1-887902-36-8

10-47

Bob

Carl

Froggie

Debbie

Evan

a[0]

a[1]

a[2]

a[3]

a[4]

low

mid

high

low

mid

high

Data pass 1 pass 2 pass 3 pass 4...

Search for "Duckie" What goes Search for "Duckie" What goes wrong? Fix code on previous slidewrong? Fix code on previous slide

low

mid

high

low...

mid...

high...

How do we fix this

defective binary search ? _____?Optional Demo: binserch.cpp