coll.push_back('b')

advertisement
26-Jul-2006
Today’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
1
Intro to the STL
Chapter 23
2
Intro to the STL (Deitel, 1112)
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
3
Intro to the STL (Deitel, 1112; Goodrich, 242)
Containers
 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.
4
Intro to the STL (Deitel, 1112)
STL 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
5
Intro to the STL (Deitel, 1125)
STL 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
6
Intro to the STL (Deitel, 1125–7)
Using a vector Object
#include <vector>
using namespace std;
int main(){
Include the header file
7
Intro to the STL (Deitel, 1125–7)
Using a vector Object
#include <vector>
using namespace std;
int main(){
vector<char> collection;
Name of the class
Instantiate a vector object
that will hold char data
The object name
Template parameter –
type of data the vector will hold
8
Intro to the STL (Deitel, 1125–7)
Using 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');
Add some data
9
Intro to the STL (Deitel, 1125–7)
Using 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;
Number of elements in
the vector = 3
10
Intro to the STL (Deitel, 1125–7)
Using 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();
Removing an element
11
Intro to the STL (Deitel, 1125–7)
Using a vector like an array
#include <vector>
using namespace std;
int main(){
vector<char> collection;
collection.resize(3);
Before using an array
index to insert values into a
vector, make sure that the
vector has enough room
for your data
12
Intro to the STL (Deitel, 1125–7)
Using 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';
Add some data by using the
assignment operator
13
Intro to the STL (Deitel, 1125–7)
Using 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;
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
14
Intro to the STL (Deitel, 1125–7)
Using 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;}
When the at() member function is used with an index, the range is
15
checked, and an out-of-range exception can be thrown.
Intro to the STL (Deitel, 1133)
STL list Class
 Contains elements in a linear sequence
 #include <list>
 list<char> collection;
list<Customer> customers;
 Works like a linked list
16
Intro to the STL (Deitel, 1133–1137, Josuttis,)
Using a list Object
#include <list>
using namespace std;
int main(){
list<char> collection;
Instantiate a list object that
will hold char data
17
Intro to the STL (Deitel, 1133–1137, Josuttis,)
Using 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');
Add some data
18
Intro to the STL (Deitel, 1133–1137, Josuttis,)
Using 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');
Removing all elements
equal to ‘b’
19
Intro to the STL (Deitel, 1133–1137, Josuttis,)
Using 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;
Will print ‘2’
20
Intro to the STL (Deitel, 1133–1137, Josuttis,)
Using 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();
} 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.
21
Intro to the STL (Deitel, 1145; Josuttis, 90, 194)
STL 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
22
Intro to the STL (Deitel, 1145; Josuttis, 90, 194)
Using a Map as an
Associative 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"];
23
Intro to the STL (Christiansen,150; Lippman,1081)
Example 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;
}
}
24
Intro to the STL (Deitel, 1117; Josuttis, 83–86)
STL 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
25
Intro to the STL (Josuttis, 83–86)
Using an STL Iterator
vector<char> coll;
coll.push_back('c');
coll.push_back('a');
coll.push_back('b');
Create a vector of chars
and put some chars in it
26
Intro to the STL (Josuttis, 83–86)
Using an STL Iterator
vector<char> coll;
coll.push_back('c');
coll.push_back('a');
coll.push_back('b');
vector<char>::iterator pos;
Instantiate an iterator that
can be used with a vector
of chars
27
Intro to the STL (Josuttis, 83–86)
Using an STL Iterator
vector<char> coll;
coll.push_back('c');
coll.push_back('a');
coll.push_back('b');
vector<char>::iterator pos;
Create a for loop
for( pos = coll.begin(); pos != coll.end(); ++pos)
28
Intro to the STL (Josuttis, 83–86)
Using 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)
Initialization
Assign a starting value to the iterator
Every collection class has a begin()
member function that returns an
iterator representing its first element.
29
Intro to the STL (Josuttis, 83–86)
Using 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)
Condition
Loop 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.
30
Intro to the STL (Josuttis, 83–86)
Using 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)
In the expression evaluated at
the end of each loop, the
iterator behaves like a pointer.
31
Intro to the STL (Josuttis, 83–86)
Using 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 << " ";
}
In the loop, we can use the iterator like
a pointer again, so that we can get the
value stored at this position.
32
Intro to the STL (Deitel, 1152; Josuttis, 94)
STL 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
33
Intro to the STL (Josuttis, 95–96)
Using STL Algorithms
vector<char> coll;
coll.push_back('c');
coll.push_back('a');
coll.push_back('b');
Create a vector of chars
and put some chars in it
vector<char>::iterator pos;
Instantiate an iterator that
can be used with a vector
of chars
34
Intro to the STL (Josuttis, 95–96)
Using 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() );
Call an STL algorithm to locate the
minimum element in a collection.
35
Intro to the STL (Josuttis, 95–96)
Using 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() );
Returns an iterator for the
position of the minimum
element.
Arguments specify the range
of elements to examine in the
collection.
36
Intro to the STL (Josuttis, 95–96)
Using 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;
Use the iterator like a pointer again, to
get the value stored at this position.
37
Intro to the STL (Josuttis, 95–96)
Using 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;
Another STL algorithm locates the
maximum element in a collection.
38
Intro to the STL (Josuttis, 95–96, 123)
Using STL Algorithms
vector<char> coll;
coll.push_back('c');
coll.push_back('a');
coll.push_back('b');
sort( coll.begin(), coll.end() );
Sorting the elements in a collection.
39
Intro to the STL (Josuttis, 95–96)
Using Arrays with STL Algorithms
char coll[] = {'c','a','a','b'};
sort( coll, coll+4 );
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
40
Intro to the STL (Josuttis, 95–96, 123)
Using 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();
}
When the elements in an STL collection are objects, a
“binary predicate” can be defined for the sort() algorithm
to use.
41
Intro to the STL (Josuttis, 95–96, 123)
Using 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();
}
A “predicate” is a function that returns a
boolean value, and they are often used
with STL algorithms.
42
Intro to the STL (Josuttis, 95–96, 123)
Using 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();
}
A “binary predicate” usually compares
an attribute of two arguments.
43
Intro to the STL (Josuttis, 95–96, 123)
Using 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 );
The name of the binary predicate is passed as the third argument
44
Intro to the STL (Josuttis, 95–96, 123)
Using STL Algorithms
vector<Customer> coll;
class Customer{
coll.push_back(Customer("Alan","Turing"));
public:
coll.push_back(Customer("Charles","Babbage"));
bool operator<( const Customer& rhs ){
return this->lname < rhs.lname;
coll.push_back(Customer("Ada","Lovelace"));
}
//...
};
sort( coll.begin(), coll.end() );
Another approach that works equally well is
to define operator< in the class, then the
criteria is not required.
45
Intro to the STL (Josuttis, 95–96, 341)
Using STL Algorithms
vector<char> coll;
coll.push_back('c');
coll.push_back('a');
coll.push_back('b');
vector<char>::iterator pos;
find() can be used to find an
element in a collection.
pos = find( coll.begin(), coll.end(), 'b' );
target
if( pos == coll.end() ) cout << "\nNot found\n";
else cout << "\nFound: " << *pos << "\n";
46
Intro to the STL (Josuttis, 95–96, 341)
Using STL Algorithms
vector<Customer> coll;
coll.push_back(Customer("Alan","Turing"));
coll.push_back(Customer("Charles","Babbage"));
coll.push_back(Customer("Ada","Lovelace"));
The target can be an object,
but only if operator== is
vector<char>::iterator pos;
defined
Customer alan("Alan","Turing");
pos = find( coll.begin(), coll.end(), alan );
class Customer{
public:
if( pos == coll.end() ) cout << "\nNot found\n";
bool operator==( const Customer& rhs ){
else( cout
<< "\nFound:
" << (*pos).toString() <<
return
(this->lname
== rhs.lname)
&&
(this->fname == rhs.fname) );
}
//...
};
"\n";
47
Intro to the STL (Josuttis, 95–96)
Using 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 );
An iterator can sometimes be used as
an argument to a member function of a
collection
48
Intro to the STL (Josuttis, 95–96)
Using STL Algorithms
vector<char> coll;
coll.push_back('c');
coll.push_back('a');
coll.push_back('a');
coll.push_back('b');
To remove all elements that have a
particular value, the remove function
can be used.
coll.erase( remove(coll.begin(),coll.end(),'a'),
coll.end() );
However, it only works properly for a
vector if it’s used with the vector’s
erase member function.
49
Intro to the STL (Josuttis, 95–96)
Using 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() );
Reversing the elements in a collection.
50
Final Exam Review
51
Final Exam Review
Final 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
52
Final Exam Review
Material 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
53
Final Exam Review
Test 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
54
Final Exam Review
Suggestions 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?
55
References
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: AddisonWesley, 1998.
56
Download