1 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 26-Jul-2006
2 Intro to the STL Chapter 23
3 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)
4 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. Intro to the STL (Deitel, 1112; Goodrich, 242)
5 STL Containers Template classes that can be used to hold collections of data vector class #include Used like an array, but dynamically re-sizable list class #include Used like a linked list set class and multiset class #include Sorts elements automatically map class and multimap class #include Associative arrays Intro to the STL (Deitel, 1112)
6 STL vector Class Contains elements in a linear sequence Its elements are accessible with operator [] #include vector collection; vector customers; Works like an array, but it is automatically re-sized when it needs more space Intro to the STL (Deitel, 1125)
7 Using a vector Object #include using namespace std; int main(){ Intro to the STL (Deitel, 1125–7) Include the header file
8 Using a vector Object #include using namespace std; int main(){ vector collection; 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
9 Using a vector Object #include using namespace std; int main(){ vector collection; collection.push_back('c'); collection.push_back('a'); collection.push_back('b'); Intro to the STL (Deitel, 1125–7) Add some data
10 Using a vector Object #include using namespace std; int main(){ vector collection; collection.push_back('c'); collection.push_back('a'); collection.push_back('b'); cout << collection.size() << endl; Intro to the STL (Deitel, 1125–7) Number of elements in the vector = 3
11 Using a vector Object #include using namespace std; int main(){ vector 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) Removing an element
12 Using a vector like an array #include using namespace std; int main(){ vector collection; collection.resize(3); 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
13 Using a vector like an array #include using namespace std; int main(){ vector collection; collection.resize(3); collection[0] = 'c'; collection[1] = 'a'; collection[2] = 'b'; Intro to the STL (Deitel, 1125–7) Add some data by using the assignment operator
14 Using a vector Object #include using namespace std; int main(){ vector 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) 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
15 Using a vector Object #include using namespace std; int main(){ vector 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) When the at() member function is used with an index, the range is checked, and an out-of-range exception can be thrown.
16 STL list Class Contains elements in a linear sequence #include list collection; list customers; Works like a linked list Intro to the STL (Deitel, 1133)
17 Using a list Object #include using namespace std; int main(){ list collection; Intro to the STL (Deitel, 1133–1137, Josuttis,) Instantiate a list object that will hold char data
18 Using a list Object #include using namespace std; int main(){ list 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,) Add some data
19 Using a list Object #include using namespace std; int main(){ list 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,) Removing all elements equal to ‘b’
20 Using a list Object #include using namespace std; int main(){ list 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,) Will print ‘2’
21 Using a list Object #include using namespace std; int main(){ list 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,) 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.
22 STL map Class STL ordered dictionary class #include map map passwords; Does not allow duplicates If duplicates are needed, use the multimap class Intro to the STL (Deitel, 1145; Josuttis, 90, 194)
23 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 password; password["Bob"] = "zebra"; map stockValue; stockValue["MSFT"] = 25.53; stockValue["IBM"] = 91.94; cout << "Microsoft price: " << stockValue["MSFT"]; Intro to the STL (Deitel, 1145; Josuttis, 90, 194)
24 Example of Using a Map int main(){ string word; map 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 ::iterator pos; for( pos=wordFrequency.begin(); pos!=wordFrequency.end(); ++pos ){ cout first second << endl; } Intro to the STL (Christiansen,150; Lippman,1081)
25 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 Intro to the STL (Deitel, 1117; Josuttis, 83–86)
26 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); Intro to the STL (Josuttis, 83–86) Create a vector of chars and put some chars in it
27 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; Intro to the STL (Josuttis, 83–86) Instantiate an iterator that can be used with a vector of chars
28 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; for( pos = coll.begin(); pos != coll.end(); ++pos) Intro to the STL (Josuttis, 83–86) Create a for loop
29 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; for( pos = coll.begin(); pos != coll.end(); ++pos) Intro to the STL (Josuttis, 83–86) Initialization Assign a starting value to the iterator Every collection class has a begin() member function that returns an iterator representing its first element.
30 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; for( pos = coll.begin(); pos != coll.end(); ++pos) Intro to the STL (Josuttis, 83–86) 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.
31 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; for( pos = coll.begin(); pos != coll.end(); ++pos) Intro to the STL (Josuttis, 83–86) In the expression evaluated at the end of each loop, the iterator behaves like a pointer.
32 Using an STL Iterator vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; for( pos = coll.begin(); pos != coll.end(); ++pos) { cout << *pos << " "; } 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.
33 STL Algorithms In the STL, algorithms are global functions STL algorithms are used with iterators #include Some STL algorithms copy count find min_element max_element reverse sort unique Intro to the STL (Deitel, 1152; Josuttis, 94)
34 Using STL Algorithms vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; 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
35 Using STL Algorithms vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; pos = min_element( coll.begin(), coll.end() ); Intro to the STL (Josuttis, 95–96) Call an STL algorithm to locate the minimum element in a collection.
36 Using STL Algorithms vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; pos = min_element( coll.begin(), coll.end() ); 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.
37 Using STL Algorithms vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; pos = min_element( coll.begin(), coll.end() ); cout << "Min = " << *pos << endl; Intro to the STL (Josuttis, 95–96) Use the iterator like a pointer again, to get the value stored at this position.
38 Using STL Algorithms vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::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) Another STL algorithm locates the maximum element in a collection.
39 Using STL Algorithms vector 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) Sorting the elements in a collection.
40 Using Arrays with STL Algorithms char coll[] = {'c','a','a','b'}; sort( coll, coll+4 ); 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
41 Using STL Algorithms vector 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) When the elements in an STL collection are objects, a “binary predicate” can be defined for the sort() algorithm to use.
42 Using STL Algorithms vector 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) A “predicate” is a function that returns a boolean value, and they are often used with STL algorithms.
43 Using STL Algorithms vector 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) A “binary predicate” usually compares an attribute of two arguments.
44 Using STL Algorithms vector 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) The name of the binary predicate is passed as the third argument
45 Using STL Algorithms vector 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) 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; } //... };
46 Using STL Algorithms vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::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) find() can be used to find an element in a collection. target
47 Using STL Algorithms vector coll; coll.push_back(Customer("Alan","Turing")); coll.push_back(Customer("Charles","Babbage")); coll.push_back(Customer("Ada","Lovelace")); vector ::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) 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) ); } //... };
48 Using STL Algorithms vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; pos = find( coll.begin(), coll.end(), 'b' ); if( pos != coll.end() ) coll.erase( pos ); Intro to the STL (Josuttis, 95–96) An iterator can sometimes be used as an argument to a member function of a collection
49 Using STL Algorithms vector coll; coll.push_back('c'); 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) 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.
50 Using STL Algorithms vector coll; coll.push_back('c'); coll.push_back('a'); coll.push_back('b'); vector ::iterator pos; reverse( coll.begin(), coll.end() ); Intro to the STL (Josuttis, 95–96) Reversing the elements in a collection.
51 Final Exam Review
52 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 Final Exam Review
53 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 Final Exam Review
54 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 Final Exam Review
55 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? Final Exam Review
56 References C++ Language Reference (MS Visual C++ Online Help), Redmond, Washington: Microsoft Corporation, Deitel, H. M., and P. J. Deitel, C++ How to Program, Fifth Edition. Upper Saddle River, NJ: Prentice Hall, Goodrich, M. T., R. Tamassia, and D. Mount, Data Structures and Algorithms in C++. Hoboken, NJ: John Wiley & Sons, Inc., Josuttis, Nicolai M., The C++ Standard Library, A Tutorial and Reference. Boston: Addison-Wesley, Lippman, Stanley B., and Josee Lajoie, C++ Primer. Boston: Addison- Wesley, 1998.