
Unit 4 Basic Collections General Concepts ¾ Templates ¾ Exceptions ¾ Iterators Collection (or Container) Classes ¾ Vectors (or Arrays) ¾ Sets ¾ Lists ¾ Maps or Tables C++ Standard Template Library (STL Overview A program usually needs to maintain a collection of some objects ¾ i.e. the group of all employees, the company’s soccer team, etc. A collection or container class is used to create and keep a collection of objects Basic collections ¾ arrays, sets, lists, tables or maps All container classes respond to the following operations: ¾ int size() ¾ int occurrences( Object ) ¾ bool find( Object ) ¾ void add( Object ) ¾ void remove( Object ) Container classes differ in (the following characteristics): ¾ size (fixed or not) ¾ ordering ¾ access methods ¾ insertion methods ¾ removal methods Unit 5 – Basic Collections 2 Templates A template is a pattern where some types are shown as parameters. To use the template the user has to provide actual types for the template parameters. Template Functions How can we define swap() to work with any type? We can define it as a template function: template <class TYPE> void swap( TYPE& x, TYPE& y ) { TYPE tmp; tmp = x; x = y; y = tmp; } Having defined this, we can now write: int a=10,b=20; Complex c(5,10), d(3,20); ... swap(a,b); // TYPE is int swap(c,d); // TYPE is Complex swap(a,c); // ERROR! no type matches ... Unit 5 – Basic Collections 3 Template Classes Like regular classes, except some types are shown as parameters. A template class declaration for the Vector class may look like the following: template <class Item> class Vector { ...} And a function definition for the constructor of Vector may look like the following: template <class Item> Vector<Item>::Vector() {...} Vector can be used as following: Vector<int> iv(40); Vector<Complex> cv(20); ... Unit 5 – Basic Collections 4 Exception Handling How should we handle an error that occurs in a method of a class? Print an error message and continue ¾ dangerous for most cases Abort the program using assert, abort or exit routines ¾ too restrictive in many cases Set some error indicator (i.e. return a special code, etc.) ¾ user may ignore it ¾ complicates code Jump to a user defined error routine using setjump or longjump ¾ unwinds the stack without deleting objects properly Use C++ Exceptions ¾ avoids all previous problems Unit 5 – Basic Collections 5 C++ Exception Principles Exceptions are objects defined in the usual way. When a function detects an error, it can throw an exception. A function call that may throw an exception is usually enclosed in a try block that is followed by one or more catch blocks. Each catch block catches one exception type. If an exception is thrown inside the try block, the first catch block that matches it is executed. If no catch block matches the exception, the (system) function terminate is called and aborts the program. Unit 5 – Basic Collections 6 Exception Example int main() A function that divide two numbers, { double num, throws an exception if denominator is 0: denom, result; cin >> num >> denom; class division_error while ( cin ) { public: { division_error() try { { } result = quotient( num, denom )m }; cout << "The quotient is " << result << endl; double quotient( double numerator, } double denominator) catch( division_error) { { if ( denominator != 0 ) cout << denom return numerator/denominator; << " is an illigal divisor; else enter new numbers : "; throw division_error(); } } cin >> num >> denom; } return 0; } Unit 5 – Basic Collections 7 Re-Throwing Exceptions Try statements may be nested. A catch block may throw a new exception or re-throw the same exception using throw; Exceptions thrown or re-thrown by a catch block are detected in the enclosing try statement. When exceptions are not caught within a function, the function terminates and the stack is unwound. Unit 5 – Basic Collections 8 Exception Specification To restrict the type of exceptions a function throws, you can place a throw list in the function header. I.e. quotient can be written: double quotient( double numerator, double denominator) throw (division_error) If no throw list is present, function can throw any exception Unit 5 – Basic Collections 9 Standard Library Exception Classes A hierarchy of exceptions is already available in standard library. Top class exception (in header <exception> ) ¾ constructor: exception( char*) ¾ accessor: char* what() Class logic_error is derived from exception ( in <stdexcept>) ¾ constructor: logic_error( string &) ¾ accessor: char* what() ¾ This is the class we use as base for all the logical error exceptions we define Class runtime_error is derived from exception ( in <stdexcept>) ¾ similar to logic_error Class bad_alloc is derived from exception ( in <new>) ¾ it is thrown by new when memory allocation fails Some exception classes derived from logic_error ( in <stdexcept>) ¾ out_of_range : indicates that array or string subscript is out of range ¾ length_error : indicates that length is larger than max allowed Some exception classes derived from runtime_error ( in <stdexcept>) ¾ overflow_error : indicates arithmetic overflow ¾ underflow_error : indicates arithmetic underflow For this course ¾ use directly the standard exceptions when it make sense define new exceptions as subclasses of logic_error or runtime_error. Unit 5 – Basic Collections 10 Division Example: Better way class division_error : public logic_error int main() { public: { division_error(string msg) : double num, logic_error(msg) denom, result; { } cin >> num >> denom; }; while ( cin ) {try double quotient(double numerator, double { denominator) result = quotient( num, denom ) { if ( denominator != 0 ) cout << "The quotient is " << return numerator/denominator; result << endl; else } throw division_error("Illegal Divisor "); catch( division_error e) } { cout << e.what() << “ by “ << denom << " ; Enter new numbers : "; } return 0; } } Unit 5 – Basic Collections 11 Vectors ( or Abstract Arrays) Most basic indexed collections have ¾ linear structure that associates each item with an integer between 0 and size-1 ¾ size is fixed, but a vector can be resized ¾ provides direct access Additional methods: Item& operator[](int) The class Vector in the examples contains a C++ implementation of the Vector using templates. A C++ dynamic array is used for a vector in this implementation. With this implementation: ¾ updating and retrieving the i-th element takes O(1) time, independent of the size ¾ but a removal or find operation takes O(n) time Implementation of a Vector: Vector files in Examples Unit 5 – Basic Collections 12 Using a Vector We can now use Vector to store int's as following: Vector<int> a(5); a[3] = 10; a[4] = a[3]; Vector<int> b(20); b = a; // b has only 5 slots now b[6] = 30 ; // will make the program abort Example: Of using Vector in another class. ¾ The class EmployeeDB could have used Vector instead of the C++ array. Unit 5 – Basic Collections 13 Sets Most basic collections: ¾ a set is a group of items with no duplicates ¾ has unbounded (but finite) size ¾ items are not ordered In math, we define sets as { 1, 2, a, b, c} or infinite sets like {x | x is an integer } Common set operations: ¾ membership true if x is in S, false otherwise ¾ union all elements in S1 or S2 ¾ intersection the elements in both S1 and S2 ¾ complement the objects not in S Unit 5 – Basic Collections 14 C++ Sets In C++ ¾ all sets are finite ¾ check membership bool find( Item ) ¾ insertion void insert Item ) ¾ removal void erase( Item) Either (concrete) arrays or linked lists can be used to implement sets. The files in the Set-Simple example contain a C++ implementations of the Set class using templates and linked lists NOTE: Any operation on a set of n items takes O(n) time. ¾ If you retrieve most of the elements most of the time, it is OK. A bag is like a set except it can contain duplicates. Implementation of a simple set :Set-Simple in Examples Unit 5 – Basic Collections 15 Iterating over a Set How can we access all the items of a Set one by one, without knowing what the structure of a set is? The simplest way to do that is to define inside the class Set: ¾ A state variable cursor that points to the current item ¾ The functions: – void start() set cursor to the first item – bool continue() returns true if there are more items; false otherwise – void next() advances cursor to next item – Object current() returns the current item So, we can write: Set<String> myset; for (myset.start(); myset.continue(); myset.next()) { … coll.current(); … } Problem with this approach: ¾ does not allow multiple iterators over the same collection Unit 5 – Basic Collections 16 Iterators: a Better Method Define an iterator object that points to the current item inside a set. Define the iterator as a class inside the Set class. Define in the Set class the methods: ¾ begin() -- returns an iterator pointing to the first element of the set ¾ end() -- returns an iterator that points "outside" the collection Define in the iretator class the operators: ¾ ++p -- moves iterator p to the next element (prefix type) ¾ p++ -- moves iterator p to the next element (postfix type) ¾ *p -- returns the item the iterator p points to. Then we can write: Set<String> myset; for (Set<String>::iterator it = myset.begin(); it != col.end(); it++) { … *it; // to access the item … } Iterators are defined in a similar way in any collection class. Implementation of a set with an iterator :Set-Iterator in Examples Unit 5 – Basic Collections 17 Lists They are collections with the following properties: ¾ their size is unbounded ¾ items are kept in sequence: each item in the middle has a next and previous Typical methods for lists are: ¾ void insert_first( Item ) ¾ void insert_last( Item) ¾ Item first() ¾ Item last() ¾ void remove_first() ¾ void remove_last() When an iterator is defined, we need to have ¾ ListIterator<Item> begin() ¾ ListIterator<Item> end() ¾ void insert(ListIterator<Item> iter, Item item ) Usually, linked lists are used to implement lists. Here, for illustration we use a doubly-linked list to implement lists.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages18 Page
-
File Size-