11-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer...
-
Upload
prudence-neal -
Category
Documents
-
view
216 -
download
2
Transcript of 11-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer...
11-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.
11-2Chapter 11 Chapter 11 A Container with IteratorsA Container with Iterators
Chapter ObjectivesChapter Objectives declare and use declare and use bagbag objects that store collections objects that store collections
of objectsof objects define classes with define classes with vectorvector data members data members implement member functions that manipulate implement member functions that manipulate
vectorsvectors implement and use iterator functions for implement and use iterator functions for
traversing over all the items in a collectiontraversing over all the items in a collection
11-3 11.1 The bag class11.1 The bag class
Programmers use manyProgrammers use many container container classes classes A class with the main purpose of storing a collection A class with the main purpose of storing a collection
of elements that can be accessed of elements that can be accessed different container classes allow different accessdifferent container classes allow different access
– for example a vector allows direct access to any elementfor example a vector allows direct access to any element
Other standard containers: stack, queue, list, and mapOther standard containers: stack, queue, list, and map The bag class is presented here as review ofThe bag class is presented here as review of
class definitionsclass definitions vectors and vector processingvectors and vector processing
It's a container class capable of storing many itemsIt's a container class capable of storing many items
11-4 A bag class A bag class continuedcontinued
A bag object A bag object as discussed in Chapter 11--there are others as discussed in Chapter 11--there are others
stores a collection of elements thatstores a collection of elements that are not in any particular orderare not in any particular order are not necessarily uniqueare not necessarily unique has operations that includehas operations that include
bag::addbag::add bag::removebag::remove bag::capacitybag::capacity bag::sizebag::size
class definition for this bag class follows class definition for this bag class follows
11-5
class bag {class bag {public:public://--constructors//--constructors bag();bag(); bag(int capacity);bag(int capacity);//--modifiers//--modifiers void add(BAG_ELEMENT_TYPE newElement);void add(BAG_ELEMENT_TYPE newElement); bool remove(BAG_ELEMENT_TYPE removalCandidate);bool remove(BAG_ELEMENT_TYPE removalCandidate);//--accessors//--accessors int capacity();int capacity(); int size();int size(); bool isEmpty();bool isEmpty();// -- iterator functions on next slide// -- iterator functions on next slideprivate:private: vector <BAG_ELEMENT_TYPE> my_data;vector <BAG_ELEMENT_TYPE> my_data; int my_size;int my_size;};};
The bag The bag class definitionclass definition add, remove
capacity, size, isDone first, next, isDone, currentItem
my_element a vector
my_size
bag
11-6 The public iterator functionsThe public iterator functions
void first();void first();// post: my_index points to the first item, or if the// post: my_index points to the first item, or if the// bag is empty, isDone would now return true// bag is empty, isDone would now return true
void next();void next();// post: point to the next item, or isDone returns true// post: point to the next item, or isDone returns true bool isDone() const;bool isDone() const;// post: Returns true if collection has been traversed// post: Returns true if collection has been traversed
BAG_ELEMENT_TYPE currentItem() const;BAG_ELEMENT_TYPE currentItem() const;// post: Returns the item pointed to by the my_index// post: Returns the item pointed to by the my_index
11-7 Client code that uses bagClient code that uses bag
#include <iostream>#include <iostream>#include <string>#include <string>using namespace std;using namespace std;
// This must precede #include "bag" (better way shown later)// This must precede #include "bag" (better way shown later)typedef string BAG_ELEMENT_TYPE;typedef string BAG_ELEMENT_TYPE; // <- for a bag of strings// <- for a bag of strings#include "bag"#include "bag"
int main()int main(){ { // This program sends all possible messages to a bag object // This program sends all possible messages to a bag object bag bagOfStrings;bag bagOfStrings; bagOfStrings.add( "A string" );bagOfStrings.add( "A string" ); bagOfStrings.add( "Another string" ); bagOfStrings.add( "Another string" ); bagOfStrings.add( "and still another" );bagOfStrings.add( "and still another" ); bagOfStrings.add( "and a fourth" );bagOfStrings.add( "and a fourth" ); bagOfStrings.remove( "and still another" ); bagOfStrings.remove( "and still another" ); // delete one// delete one bagOfStrings.remove( "I'm not in the bag!" ); bagOfStrings.remove( "I'm not in the bag!" ); // can't // can't return 0;return 0;}}
11-8 A bag of intsA bag of ints
A bag object stores a collection objectsA bag object stores a collection objects To store int objects for example, do this:To store int objects for example, do this:
typedef int BAG_ELEMENT_TYPE;typedef int BAG_ELEMENT_TYPE; #include "bag"#include "bag"
int main()int main() {{ bag bagOfInts( 100 );bag bagOfInts( 100 ); bagOfInts.add( 72 ); bagOfInts.add( 72 ); bagOfInts.add( 97 );bagOfInts.add( 97 ); //...//...
11-9 11.1.1 The bag Constructors11.1.1 The bag Constructors
The constructors create an empty bagThe constructors create an empty bagbag::bag()bag::bag(){ { // Default is an empty bag with capacity 16// Default is an empty bag with capacity 16 my_size = 0;my_size = 0; my_data.resize(16);my_data.resize(16);}}
bag::bag(int initialCapacity)bag::bag(int initialCapacity){ { // Create an empty bag of any capacity desired// Create an empty bag of any capacity desired my_size = 0;my_size = 0; my_data.resize(initialCapacity);my_data.resize(initialCapacity);}}
bag default; bag default; // call default constructor// call default constructor bag hold500(500); bag hold500(500); // construct with one argument// construct with one argument
11-1011.1.2 The bag Modifying 11.1.2 The bag Modifying Member FunctionsMember Functions
The The bag::addbag::add operation adds all new elements to the operation adds all new elements to the "end" of the vector. If there is no room, the vector is resized"end" of the vector. If there is no room, the vector is resized
void bag::add(BAG_ELEMENT_TYPE newElement)void bag::add(BAG_ELEMENT_TYPE newElement){ { // First, increase the bag capacity if necessary// First, increase the bag capacity if necessary if(my_size >= my_data.capacity())if(my_size >= my_data.capacity()) {{ my_capacity = 2 * my_data.capacity();my_capacity = 2 * my_data.capacity(); my_data.resize( my_capacity );my_data.resize( my_capacity ); }}
// Store argument into vector of BAG_ELEMENT_TYPEs...// Store argument into vector of BAG_ELEMENT_TYPEs... my_data[my_size] = newElement;my_data[my_size] = newElement; // ...and make sure my_size is always increased by +1:// ...and make sure my_size is always increased by +1: my_size++;my_size++;}}
11-11 bag::removebag::remove
bag::removebag::remove uses sequential search to find uses sequential search to find the element to be removedthe element to be removed
If the element is foundIf the element is found move the last element (move the last element (my_data[my_size-1]my_data[my_size-1]) )
into the location of the removal elementinto the location of the removal element decrease decrease my_sizemy_size by 1 by 1
does the following code look familiar? does the following code look familiar?
11-12 bag::removebag::remove
bool bag::remove(BAG_ELEMENT_TYPE removalCandidate)bool bag::remove(BAG_ELEMENT_TYPE removalCandidate){{ int subscript = 0;int subscript = 0; // Sequentially search for removalCandidate// Sequentially search for removalCandidate while( (subscript < my_size)while( (subscript < my_size) && (my_data[subscript] != removalCandidate)) {&& (my_data[subscript] != removalCandidate)) { subscript++;subscript++; }} if(subscript == my_size) if(subscript == my_size) // removalCandidate not found// removalCandidate not found return false;return false; else { else { // move last element to removalCandidate's spot// move last element to removalCandidate's spot my_data[subscript] = my_data[my_size-1];my_data[subscript] = my_data[my_size-1]; // and then decrease size by 1// and then decrease size by 1 my_size--;my_size--; // report success to the message sender// report success to the message sender return true;return true; }}}}
11-13 The state of bagOfStrings before The state of bagOfStrings before removing "Another string"removing "Another string"
Data Members State
my_data[0] "A string"
my_data[1] "Another string"
my_data[2] "and still another"
my_data[3] "and a fourth"
…
my_size 4
local objects in bag::removeremovalCandidate "Another string"
subscript 1
11-14
"Another string"
The state after removing The state after removing "another string""another string"
Wipe out "Another string"
No longer meaningful
Decrease size
1. Find removalCandidate in my_data[1]
2. Overwrite it with the "last" bag element and decrease size
my_data[0] "A string"my_data[1] "And a fourth"my_data[2] "and still another"my_data[3] "And a fourth"...my_size 3
11-1511.1.3 The bag Accessor 11.1.3 The bag Accessor functionsfunctions
int bag::capacity() constint bag::capacity() const{ { // Return how many elements could be stored// Return how many elements could be stored return my_data.capacity(); return my_data.capacity(); }}
int bag::size() constint bag::size() const{ { // Return how many elements are in the bag// Return how many elements are in the bag return my_size;return my_size;}}
bool bag::isEmpty() constbool bag::isEmpty() const{ { // Return true if there are 0 elements in the bag// Return true if there are 0 elements in the bag return my_size == 0; return my_size == 0; }}
11-16 11.2 The Iterator Pattern11.2 The Iterator Pattern
vectors have subscripts for iterating over all vectors have subscripts for iterating over all the meaningful elementsthe meaningful elements
standard containers, including vectors use a standard containers, including vectors use a separate iterator class separate iterator class more latermore later
bags use member functionsbags use member functionsfirstfirst
isDoneisDone
currentItemcurrentItem
nextnext
11-17 Iterating over items in a bagIterating over items in a bag
bag aBag;bag aBag; int sum = 0;int sum = 0; int n = 9;int n = 9; for(int j = 1; j <= n; j=j+2)for(int j = 1; j <= n; j=j+2) {{ aBag.add(j);aBag.add(j); } } cout << "Iterate over the entire collection" << endl;cout << "Iterate over the entire collection" << endl; for( for( aBag.first()aBag.first(); ; ! aBag.isDone()! aBag.isDone(); ; aBag.next() aBag.next() )) {{ cout.width(4);cout.width(4); // reference "current" bag element// reference "current" bag element cout << cout << aBag.currentItem()aBag.currentItem(); ; // reference it again // reference it again sum = sum + sum = sum + aBag.currentItem()aBag.currentItem(); ; }} cout << "\nSum: " << sum << endl;cout << "\nSum: " << sum << endl;
Output ?
Demonstrate testbag.cpp
11-18 The iterator implementationsThe iterator implementations
void bag::first()void bag::first(){ { // Set internal index to reference the 1st element// Set internal index to reference the 1st element my_index = 0;my_index = 0;}}
bool bag::isDone() constbool bag::isDone() const{ { // Return true if previous next was the last element// Return true if previous next was the last element return my_index >= my_size;return my_index >= my_size;}}
void bag::next()void bag::next(){ { // Set internal index to reference the next element// Set internal index to reference the next element // or to allow isDone to return true// or to allow isDone to return true my_index++;my_index++;} }
BAG_ELEMENT_TYPE bag::currentItem() constBAG_ELEMENT_TYPE bag::currentItem() const{ { // Set internal index to reference the 1st element// Set internal index to reference the 1st element return my_data[my_index];return my_data[my_index];}}
11-19The Iterator pattern will be The Iterator pattern will be repeated repeated as are all patternsas are all patterns
The iterator pattern will be used againThe iterator pattern will be used again In Chapter 13: Object-Oriented Software In Chapter 13: Object-Oriented Software
DevelopmentDevelopment to display all CDs in a CD collectionto display all CDs in a CD collection to display all track in a CDto display all track in a CD
In Section 14.2In Section 14.2 iterator objects are used to traverse the elements in the iterator objects are used to traverse the elements in the
standard C++ containers such as vector and liststandard C++ containers such as vector and list– the iterator pattern is implemented quite differentlythe iterator pattern is implemented quite differently