Page 1
1
Today’s ObjectivesToday’s Objectives
Announcements• The Final Exam will be on Monday, 31-Jul, at 6 p.m. –
There is no alternate time and no makeup!
Intro to the Standard Template Library (STL) (Ch. 21)• Containers
– vector class– list class– map class
• Iterators• Algorithms
Final Exam Review
26-Jul-200626-Jul-2006
Page 2
2
Intro to the STLIntro to the STL
Chapter 23
Page 3
3
Standard Template Library (STL)Standard Template Library (STL)
Part of the C++ standard library
Defines reusable components that we can add to our programs
Three types of components in the STL• Containers• Iterators• Algorithms
Intro to the STL (Deitel, 1112)Intro to the STL (Deitel, 1112)
Page 4
4
ContainersContainers
Container = a data structure that stores a collection of objects
The stored objects are called “elements” Examples of containers
• Array• vector• Classes like RentalItemList• Linked list
Bottom line – Containers are used a lot in our programs, so we could save time if we had a library of readymade container classes that are guaranteed to work correctly and efficiently.
Intro to the STL (Deitel, 1112; Goodrich, 242)Intro to the STL (Deitel, 1112; Goodrich, 242)
Page 5
5
STL ContainersSTL Containers
Template classes that can be used to hold collections of data vector class
• #include <vector>• Used like an array, but dynamically re-sizable
list class• #include <list>• Used like a linked list
set class and multiset class• #include <set>• Sorts elements automatically
map class and multimap class• #include <map>• Associative arrays
Intro to the STL (Deitel, 1112)Intro to the STL (Deitel, 1112)
Page 6
6
STL vector ClassSTL vector Class
Contains elements in a linear sequence Its elements are accessible with operator[]
#include <vector>
vector<char> collection;vector<Customer> customers;
Works like an array, but it is automatically re-sized when it needs more space
Intro to the STL (Deitel, 1125)Intro to the STL (Deitel, 1125)
Page 7
7
Using a vector ObjectUsing a vector Object
#include <vector>using namespace std;int main(){
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
Include the header file
Page 8
8
Using a vector ObjectUsing a vector Object
#include <vector>using namespace std;int main(){
vector<char> collection;
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
Instantiate a vector object that will hold char data
Name of the class The object name
Template parameter – type of data the vector will hold
Page 9
9
Using a vector ObjectUsing a vector Object
#include <vector>using namespace std;int main(){
vector<char> collection;collection.push_back('c');collection.push_back('a');collection.push_back('b');
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
Add some data
Page 10
10
Using a vector ObjectUsing a vector Object
#include <vector>using namespace std;int main(){
vector<char> collection;collection.push_back('c');collection.push_back('a');collection.push_back('b');cout << collection.size() << endl;
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
Number of elements in the vector = 3
Page 11
11
Using a vector ObjectUsing a vector Object
#include <vector>using namespace std;int main(){
vector<char> collection;collection.push_back('c');collection.push_back('a');collection.push_back('b');cout << collection.size() << endl;collection.pop_back();
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
Removing an element
Page 12
12
Using a vector like an arrayUsing a vector like an array
#include <vector>using namespace std;int main(){
vector<char> collection;collection.resize(3);
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
Before using an array index to insert values into a vector, make sure that the vector has enough room for your data
Page 13
13
Using a vector like an arrayUsing a vector like an array
#include <vector>using namespace std;int main(){
vector<char> collection;collection.resize(3);collection[0] = 'c';collection[1] = 'a';collection[2] = 'b';
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
Add some data by using the assignment operator
Page 14
14
Using a vector ObjectUsing a vector Object
#include <vector>using namespace std;int main(){
vector<char> collection;collection.resize(3);collection[0] = 'c';collection[1] = 'a';collection[2] = 'b';for( int i=0; i<collection.size(); ++i )
cout << collection[i] << endl;
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
We can refer to each element in the vector by using an index, just like with an array
• The range is not checked, so an out-of-range error can occur
Page 15
15
Using a vector ObjectUsing a vector Object
#include <vector>using namespace std;int main(){
vector<char> collection;collection.resize(3);collection[0] = 'c';collection[1] = 'a';collection[2] = 'b';for( int i=0; i<collection.size(); ++i )
cout << collection[i] << endl;try{
cout << collection.at(256) << endl;}catch( out_of_range e ){cout << e.what() << endl;}
Intro to the STL (Deitel, 1125–7)Intro to the STL (Deitel, 1125–7)
When the at() member function is used with an index, the range is checked, and an out-of-range exception can be thrown.
Page 16
16
STL list ClassSTL list Class
Contains elements in a linear sequence
#include <list>
list<char> collection;list<Customer> customers;
Works like a linked list
Intro to the STL (Deitel, 1133)Intro to the STL (Deitel, 1133)
Page 17
17
Using a list ObjectUsing a list Object
#include <list>using namespace std;int main(){
list<char> collection;
Intro to the STL (Deitel, 1133–1137, Josuttis,)Intro to the STL (Deitel, 1133–1137, Josuttis,)
Instantiate a list object that will hold char data
Page 18
18
Using a list ObjectUsing a list Object
#include <list>using namespace std;int main(){
list<char> collection;collection.push_back('c');collection.push_front('a');collection.push_front('b');collection.push_back('b');
Intro to the STL (Deitel, 1133–1137, Josuttis,)Intro to the STL (Deitel, 1133–1137, Josuttis,)
Add some data
Page 19
19
Using a list ObjectUsing a list Object
#include <list>using namespace std;int main(){
list<char> collection;collection.push_back('c');collection.push_front('a');collection.push_front('b');collection.push_back('b');collection.remove('b');
Intro to the STL (Deitel, 1133–1137, Josuttis,)Intro to the STL (Deitel, 1133–1137, Josuttis,)
Removing all elements equal to ‘b’
Page 20
20
Using a list ObjectUsing a list Object
#include <list>using namespace std;int main(){
list<char> collection;collection.push_back('c');collection.push_front('a');collection.push_front('b');collection.push_back('b');collection.remove('b');cout << collection.size() << endl;
Intro to the STL (Deitel, 1133–1137, Josuttis,)Intro to the STL (Deitel, 1133–1137, Josuttis,)
Will print ‘2’
Page 21
21
Using a list ObjectUsing a list Object
#include <list>using namespace std;int main(){
list<char> collection;collection.push_back('c');collection.push_front('a');collection.push_front('b');collection.push_back('b');collection.remove('b');cout << collection.size() << endl;while( !collection.empty() ){
cout << collection.front() << endl;collection.pop_front();
}}
Intro to the STL (Deitel, 1133–1137, Josuttis,)Intro to the STL (Deitel, 1133–1137, Josuttis,)
Since access by operator[] is not allowed, this loop iterates through the list by removing each element, a better way is to use an iterator.
Page 22
22
STL map ClassSTL map Class
STL ordered dictionary class
#include <map>
map<keyType,elementType>
map<string,string> passwords;
Does not allow duplicates• If duplicates are needed, use the multimap
class
Intro to the STL (Deitel, 1145; Josuttis, 90, 194)Intro to the STL (Deitel, 1145; Josuttis, 90, 194)
Page 23
23
Using a Map as anAssociative ArrayUsing a Map as anAssociative Array
Associative array = an array where the index can be any datatype
Insertion is done with operator[] Examples
map<string,string> password;password["Bob"] = "zebra";
map<string,double> stockValue;stockValue["MSFT"] = 25.53;stockValue["IBM"] = 91.94;cout << "Microsoft price: " << stockValue["MSFT"];
Intro to the STL (Deitel, 1145; Josuttis, 90, 194)Intro to the STL (Deitel, 1145; Josuttis, 90, 194)
Page 24
24
Example of Using a MapExample of Using a Map
int main(){
string word; map<string,int> wordFrequency; //Count frequency of each word
ifstream bookFile( "MobyDick.txt" ); while( !bookFile.eof() ) {
bookFile >> word;wordFrequency[word]++;
} bookFile.close(); cout << "\nUnique words = " << wordFrequency.size() << endl;
map<string,int>::iterator pos; for( pos=wordFrequency.begin(); pos!=wordFrequency.end(); ++pos ){
cout << pos->first << " " << pos->second << endl; }}
Intro to the STL (Christiansen,150; Lippman,1081)Intro to the STL (Christiansen,150; Lippman,1081)
Page 25
25
STL IteratorsSTL Iterators
An iterator is a class used to create objects that give us access to the elements inside a container
They are called “iterators” because they are often used to sequentially iterate or “loop” through all the elements in a container
Iterators are implemented as part of the container class with which we use them – all container classes have them
Some types of iterators that may be used with most container classes• iterator• const_iterator• reverse_iterator
Intro to the STL (Deitel, 1117; Josuttis, 83–86)Intro to the STL (Deitel, 1117; Josuttis, 83–86)
Page 26
26
Using an STL IteratorUsing an STL Iterator
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
Intro to the STL (Josuttis, 83–86)Intro to the STL (Josuttis, 83–86)
Create a vector of chars and put some chars in it
Page 27
27
Using an STL IteratorUsing an STL Iterator
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
Intro to the STL (Josuttis, 83–86)Intro to the STL (Josuttis, 83–86)
Instantiate an iterator that can be used with a vector of chars
Page 28
28
Using an STL IteratorUsing an STL Iterator
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
for( pos = coll.begin(); pos != coll.end(); ++pos)
Intro to the STL (Josuttis, 83–86)Intro to the STL (Josuttis, 83–86)
Create a for loop
Page 29
29
Using an STL IteratorUsing an STL Iterator
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
for( pos = coll.begin(); pos != coll.end(); ++pos)
Intro to the STL (Josuttis, 83–86)Intro to the STL (Josuttis, 83–86)
InitializationAssign a starting value to the iterator
Every collection class has a begin() member function that returns an iterator representing its first element.
Page 30
30
Using an STL IteratorUsing an STL Iterator
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
for( pos = coll.begin(); pos != coll.end(); ++pos)
Intro to the STL (Josuttis, 83–86)Intro to the STL (Josuttis, 83–86)
ConditionLoop is executed only if this is true
Every collection class has a end() member function that returns an iterator representing the position after the last element.
Page 31
31
Using an STL IteratorUsing an STL Iterator
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
for( pos = coll.begin(); pos != coll.end(); ++pos)
Intro to the STL (Josuttis, 83–86)Intro to the STL (Josuttis, 83–86)
In the expression evaluated at the end of each loop, the iterator behaves like a pointer.
Page 32
32
Using an STL IteratorUsing an STL Iterator
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
for( pos = coll.begin(); pos != coll.end(); ++pos){
cout << *pos << " ";}
Intro to the STL (Josuttis, 83–86)Intro to the STL (Josuttis, 83–86)
In the loop, we can use the iterator like a pointer again, so that we can get the value stored at this position.
Page 33
33
STL AlgorithmsSTL Algorithms
In the STL, algorithms are global functions STL algorithms are used with iterators #include <algorithm> Some STL algorithms
• copy• count• find• min_element• max_element• reverse• sort• unique
Intro to the STL (Deitel, 1152; Josuttis, 94)Intro to the STL (Deitel, 1152; Josuttis, 94)
Page 34
34
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
Create a vector of chars and put some chars in it
Instantiate an iterator that can be used with a vector of chars
Page 35
35
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
pos = min_element( coll.begin(), coll.end() );
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
Call an STL algorithm to locate the minimum element in a collection.
Page 36
36
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
pos = min_element( coll.begin(), coll.end() );
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
Returns an iterator for the position of the minimum element.
Arguments specify the range of elements to examine in the collection.
Page 37
37
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
pos = min_element( coll.begin(), coll.end() );cout << "Min = " << *pos << endl;
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
Use the iterator like a pointer again, to get the value stored at this position.
Page 38
38
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
pos = min_element( coll.begin(), coll.end() );cout << "Min = " << *pos << endl;
pos = max_element( coll.begin(), coll.end() );cout << "Max = " << *pos << endl;
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
Another STL algorithm locates the maximum element in a collection.
Page 39
39
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
sort( coll.begin(), coll.end() );
Intro to the STL (Josuttis, 95–96, 123)Intro to the STL (Josuttis, 95–96, 123)
Sorting the elements in a collection.
Page 40
40
Using Arrays with STL AlgorithmsUsing Arrays with STL Algorithms
char coll[] = {'c','a','a','b'};
sort( coll, coll+4 );
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
The first argument must be a pointer to the beginning element in the range of elements to be sorted
The second argument must be a pointer to the position after the last element
Page 41
41
Using STL AlgorithmsUsing STL Algorithms
vector<Customer> coll;
coll.push_back(Customer("Alan","Turing"));
coll.push_back(Customer("Charles","Babbage"));
coll.push_back(Customer("Ada","Lovelace"));
bool criteria(const Customer& c1, const Customer& c2){return c1.getLastName() < c2.getLastName();
}
Intro to the STL (Josuttis, 95–96, 123)Intro to the STL (Josuttis, 95–96, 123)
When the elements in an STL collection are objects, a “binary predicate” can be defined for the sort() algorithm to use.
Page 42
42
Using STL AlgorithmsUsing STL Algorithms
vector<Customer> coll;
coll.push_back(Customer("Alan","Turing"));
coll.push_back(Customer("Charles","Babbage"));
coll.push_back(Customer("Ada","Lovelace"));
bool criteria(const Customer& c1, const Customer& c2){return c1.getLastName() < c2.getLastName();
}
Intro to the STL (Josuttis, 95–96, 123)Intro to the STL (Josuttis, 95–96, 123)
A “predicate” is a function that returns a boolean value, and they are often used with STL algorithms.
Page 43
43
Using STL AlgorithmsUsing STL Algorithms
vector<Customer> coll;
coll.push_back(Customer("Alan","Turing"));
coll.push_back(Customer("Charles","Babbage"));
coll.push_back(Customer("Ada","Lovelace"));
bool criteria(const Customer& c1, const Customer& c2){return c1.getLastName() < c2.getLastName();
}
Intro to the STL (Josuttis, 95–96, 123)Intro to the STL (Josuttis, 95–96, 123)
A “binary predicate” usually compares an attribute of two arguments.
Page 44
44
Using STL AlgorithmsUsing STL Algorithms
vector<Customer> coll;
coll.push_back(Customer("Alan","Turing"));
coll.push_back(Customer("Charles","Babbage"));
coll.push_back(Customer("Ada","Lovelace"));
bool criteria(const Customer& c1, const Customer& c2){return c1.getLastName() < c2.getLastName();
}
sort( coll.begin(), coll.end(), criteria );
Intro to the STL (Josuttis, 95–96, 123)Intro to the STL (Josuttis, 95–96, 123)
The name of the binary predicate is passed as the third argument
Page 45
45
Using STL AlgorithmsUsing STL Algorithms
vector<Customer> coll;
coll.push_back(Customer("Alan","Turing"));
coll.push_back(Customer("Charles","Babbage"));
coll.push_back(Customer("Ada","Lovelace"));
sort( coll.begin(), coll.end() );
Intro to the STL (Josuttis, 95–96, 123)Intro to the STL (Josuttis, 95–96, 123)
Another approach that works equally well is to define operator< in the class, then the criteria is not required.
class Customer{public:
bool operator<( const Customer& rhs ){return this->lname < rhs.lname;
}//...};
class Customer{public:
bool operator<( const Customer& rhs ){return this->lname < rhs.lname;
}//...};
Page 46
46
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
pos = find( coll.begin(), coll.end(), 'b' );
if( pos == coll.end() ) cout << "\nNot found\n";else cout << "\nFound: " << *pos << "\n";
Intro to the STL (Josuttis, 95–96, 341)Intro to the STL (Josuttis, 95–96, 341)
find() can be used to find an element in a collection.
target
Page 47
47
Using STL AlgorithmsUsing STL Algorithms
vector<Customer> coll;coll.push_back(Customer("Alan","Turing"));coll.push_back(Customer("Charles","Babbage"));coll.push_back(Customer("Ada","Lovelace"));
vector<char>::iterator pos;Customer alan("Alan","Turing");pos = find( coll.begin(), coll.end(), alan );
if( pos == coll.end() ) cout << "\nNot found\n";else cout << "\nFound: " << (*pos).toString() << "\n";
Intro to the STL (Josuttis, 95–96, 341)Intro to the STL (Josuttis, 95–96, 341)
The target can be an object, but only if operator== is defined
class Customer{public: bool operator==( const Customer& rhs ){ return ( (this->lname == rhs.lname) && (this->fname == rhs.fname) ); }//...};
class Customer{public: bool operator==( const Customer& rhs ){ return ( (this->lname == rhs.lname) && (this->fname == rhs.fname) ); }//...};
Page 48
48
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
pos = find( coll.begin(), coll.end(), 'b' );
if( pos != coll.end() )coll.erase( pos );
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
An iterator can sometimes be used as an argument to a member function of a collection
Page 49
49
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('a');coll.push_back('b');
coll.erase( remove(coll.begin(),coll.end(),'a'), coll.end() );
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
To remove all elements that have a particular value, the remove function can be used.
However, it only works properly for a vector if it’s used with the vector’s erase member function.
Page 50
50
Using STL AlgorithmsUsing STL Algorithms
vector<char> coll;coll.push_back('c');coll.push_back('a');coll.push_back('b');
vector<char>::iterator pos;
reverse( coll.begin(), coll.end() );
Intro to the STL (Josuttis, 95–96)Intro to the STL (Josuttis, 95–96)
Reversing the elements in a collection.
Page 51
51
Final Exam ReviewFinal Exam Review
Page 52
52
Final ExamFinal Exam
30% of your grade for the course Jul. 31 at 6 p.m. in the regular classroom No makeup exam No alternate time Closed book Closed notes
Final Exam ReviewFinal Exam Review
Page 53
53
Material CoveredMaterial Covered
Anything in the slides and handouts
Deitel text, chapters 1–18, 21.1–21.4, and 23
Most of the questions will focus on the material covered since the Midterm Exam, but it is still important to know the material from the first part since it provides the foundation
Final Exam ReviewFinal Exam Review
Page 54
54
Test FormatTest Format
Approximately 20 questions Short C++ programs
• Write the C++ code for a derived class from a given UML class diagram – the code should be complete and compilable
• Write a short C++ code fragment that is complete and compilable
Short answers – write a line of C++ code Simple UML diagrams – e.g. draw a diagram showing
composition (has-a) or inheritance (is-a) associations Multiple choice Locate errors in code
Final Exam ReviewFinal Exam Review
Page 55
55
Suggestions for StudyingSuggestions for Studying
Look at the Learning Objectives on the course syllabus Concentrate your study time on the major topics that we have
covered in class Use the Final Exam Review handout as a study guide – download it
from the Files area of our Discussion Group Make sure that you know what the object-oriented C++ features do
and how to use them• Can you write a C++ derived class, including the data members and
fully implemented member functions?• Do you know how virtual member functions work?• Can you instantiate an object from a template class?• Do you know how to use a try-catch block with exceptions?• Do you know how to open a file for input?• Do you know how to add a new Node to a linked list?
Final Exam ReviewFinal Exam Review
Page 56
56
ReferencesReferences
C++ Language Reference (MS Visual C++ Online Help), Redmond, Washington: Microsoft Corporation, 2001.
Deitel, H. M., and P. J. Deitel, C++ How to Program, Fifth Edition. Upper Saddle River, NJ: Prentice Hall, 2005.
Goodrich, M. T., R. Tamassia, and D. Mount, Data Structures and Algorithms in C++. Hoboken, NJ: John Wiley & Sons, Inc., 2004.
Josuttis, Nicolai M., The C++ Standard Library, A Tutorial and Reference. Boston: Addison-Wesley, 1999.
Lippman, Stanley B., and Josee Lajoie, C++ Primer. Boston: Addison-Wesley, 1998.