Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Exceptions, Templates and Standard Template Library - Lecture Slides | CS 1410, Study notes of Computer Science

Material Type: Notes; Professor: Allan; Class: Introduction to Computer Science--CS 2; Subject: Computer Science; University: Utah State University; Term: Unknown 1989;

Typology: Study notes

Pre 2010

Uploaded on 07/30/2009

koofers-user-jr2-2
koofers-user-jr2-2 🇺🇸

10 documents

1 / 28

Toggle sidebar

Related documents


Partial preview of the text

Download Exceptions, Templates and Standard Template Library - Lecture Slides | CS 1410 and more Study notes Computer Science in PDF only on Docsity! 1 Chapter 16 Exceptions, Templates, and the Standard Template Library (STL) CS 1410 - SJAllan Chapter 16 2 Assert #include <cassert> assert( boolean expression ); If the value of the expression is false, assert prints an error message and calls function abort 2 CS 1410 - SJAllan Chapter 16 3 Assert Example int totalDays( int days, int weeks ) { assert ( ( days < 0 ) || ( days > 7 ) ) return ( 7 * weeks + days ); } // totalDays CS 1410 - SJAllan Chapter 16 4 Exceptions Up to now, we have checked for errors by placing if statements that checked for the condition or by using assert statements Exceptions give us more flexibility to deal with errors 5 CS 1410 - SJAllan Chapter 16 9 Exceptions – Example int totalDays( int days, int weeks ) { if ( ( days < 0 ) || ( days > 7 ) ) thrown "invalid number of days"; else return ( 7 * weeks + days ); } // totalDays CS 1410 - SJAllan Chapter 16 10 Exceptions – Example try { totDays = totalDays( days, weeks ); cout << "Total days: " << totDays; } // try catch ( char *msg ) { cout << "Error: " << msg; } // catch 6 CS 1410 - SJAllan Chapter 16 11 Exceptions – What Happens 1. The try block is entered and the totalDays function is called 2. If the first parameter is between 0 and 7, the total number of days is returned and the catch block is skipped over (no exception thrown) 3. If an exception is thrown, the function and try block are exited and the catch blocks are scanned for first one that matches that data type of the thrown exception o The catch block executes o The statement following is then executed CS 1410 - SJAllan Chapter 16 12 Exceptions - Notes Predefined functions, such as new, may throw exceptions The value that is thrown does not need to be used in the catch block In this case, no name is needed in the catch parameter definition The catch block parameter definition does need the type of exception being caught 7 CS 1410 - SJAllan Chapter 16 13 Exceptions Not Caught? An exception will not be caught if: It is thrown from outside a try block There is no catch block that matches the data type of the thrown exception If an exception is not caught, the program terminates CS 1410 - SJAllan Chapter 16 14 Exceptions and Objects An exception class can be defined in a class and thrown as an exception by a member function An exception class may have: No members – used only to signal an error Members – pass error data to catch block A class can be more than one exception class 10 CS 1410 - SJAllan Chapter 16 19 IntRangeMain.cpp – Program try { userValue = range.getInput(); cout << "You entered " << uservalue << endl; } // try catch ( IntRange::OutOfRange ex ) { cout << "The value " << ex.value << " is out of range." << endl; } // catch cout << "End of program." << endl; return 0; } // main CS 1410 - SJAllan Chapter 16 20 IntRangeMain.cpp – Output Enter a value in the range 5 – 10: 12[Enter] The value 12 is out of range. End of the program. 11 CS 1410 - SJAllan Chapter 16 21 Function Templates A function template is a pattern for a function that can work with many data types When written, parameters are left for the data types When called, the compiler generates code for the specific data types in the function call CS 1410 - SJAllan Chapter 16 22 Function Template Example Template <class T> T times10( T num ) { return 10 * num; } // time10 template prefix generic data type type parameter double times10 ( double num ) { return 10 * num; } // times10 int times10( int num) { return 10 * num; } // times10 What gets generated when times10 is call with a double? What gets generated when times10 is called with an int? 12 CS 1410 - SJAllan Chapter 16 23 Template Example Suppose we want to write a generic function that prints the elements of an array regardless of the type of the element CS 1410 - SJAllan Chapter 16 24 PrintArray.cpp – Program #include <iostream> #include <cstring> using namespace std; template< class T> void printArray ( const T *array, const int size ) { for ( int i = 0; i < size; i++ ) { if ( !( i % 10 ) ) cout << endl; cout << array[i] << " "; } // for cout << endl; } // printArray 15 CS 1410 - SJAllan Chapter 16 29 Operators in Template If arithmetic or relational operators are used in templates, they must be defined for the different types of the templates If the operators are not defined for a particular type, the compiler generates an error CS 1410 - SJAllan Chapter 16 30 Overloading Function Template Function templates may be overloaded Each template must have a unique parameter list template <class T> T sumAll( T num ) … template <class T1, class T2> T1 sumAll( T1 num1, T2 num2 ) … 16 CS 1410 - SJAllan Chapter 16 31 Overloading Function Templates template<class T> T sum ( T val1, T val2 ) { return val1 + val2; } // sum template<class T> T sum ( T val1, T val2, T val3 ) { return val1 + val2 + val3; } // sum CS 1410 - SJAllan Chapter 16 32 Overloading Class Template All data types specified in the template prefix must be used in the template definition Function calls must pass parameters for all data types specified in the template prefix Like regular functions, function templates must be defined before being called 17 CS 1410 - SJAllan Chapter 16 33 More on Function Templates A function template is a pattern No actual code is generated until the function named in the template is called A function template uses no memory When passing a class object to a function template, ensure that all operators in the template are defined or overloaded in the class definition CS 1410 - SJAllan Chapter 16 34 Where to Start When Defining Templates Templates are often appropriate for multiple functions that perform the same task with different parameter data types Develop the function using usual data types first, then convert it to a template: Add template prefix Convert data type names in the function to a type parameter (i.e., a T type) in the template 20 CS 1410 - SJAllan Chapter 16 39 SimpleVector.h – Program template <class T> SimpleVector<T>::SimpleVector ( const SimpleVector &obj ) { arraySize = obj.arraySize; aptr = new T [ arraySize ]; if ( aptr == NULL ) memError( ); for ( int i; i < arraySize; i++ ) *( aptr + i ) = *( obj.aptr + i ); } // SimpleVector::SimpleVector template <class T> T &SimpleVector<T>::operator[] ( const int &sub ) { if ( sub < 0 || sub >= arraySize ) subError( ); return aptr[sub]; } // SimpleVector::operator[] CS 1410 - SJAllan Chapter 16 40 SimpleVector.h – Program template <class T> T &SimpleVector<t>::getElementAt( const int &sub ) { return operator[]( sub ); } // SimpleVector<T>::getElementAt template <class T> void SimpleVector<T>::memError( void ) { cout << "ERROR: Cannot allocate memory.\n"; exit( 1 ); } // SimpleVector<T>::memError template <class T> void SimpleVector<T>::subError( void ) { cout << "ERROR: Subscript out of range.\n"; exit( 1 ); } // SimpleVector<T>::subError 21 CS 1410 - SJAllan Chapter 16 41 Declaring Objects of Class Templates The declaration of class templates is a little different Consider the following examples: SimpleVector<int> intTable ( 10 ); SimpleVector<float> floatTable ( 10 ); In these, the parameter inside the angle brackets replaces the T in the previous declarations CS 1410 - SJAllan Chapter 16 42 Class Templates and Inheritance Class templates can inherit from other class templates: template <class T> class SimpleVector { … }; class SearchableVector : public SimpleVector<T> { … }; Must use type parameter T everywhere the base class name is used in the derived class 22 CS 1410 - SJAllan Chapter 16 43 SearchableVector.h – Program #ifndef SEARCHABLEVECTOR_H #define SEARCHABLEVECTOR_H #include "SimpleVector.h" template <class T> class SearchableVector : public SimpleVector<T> { public: SearchableVector ( int s ) : SimpleVector<T>( s ) { } SearchableVector ( SearchableVector & ); SearchableVector ( SimpleVector<T> &obj ) : SimpleVector<T>( obj ) { } int findItem ( T ); }; // SearchableVector CS 1410 - SJAllan Chapter 16 44 SearchableVector.h – Program template <class T> SearchableVector<T>::SearchableVector ( SearchableVector &obj) : SimpleVector<T>( obj.size() ) { for ( int i = 0; i < this->size(); i++ ) this->operator[]( i ) = obj[ i ]; } // SearchableVector template <class T> int SearchableVector<T>::findItem ( T item ) { for ( int i = 0; i < size(); i++ ) if ( getElementAt( i ) == item ) return i; return –1; } // findItem 25 CS 1410 - SJAllan Chapter 16 49 Associative Containers Maps a set of keys to data elements. Many keys per data element are allowed. Duplicates are allowed. multimap Maps a set of keys to data elements. Only one key per data element is allowed. Duplicates are not allowed. map Stores a set of keys. Duplicates are allowed.multiset Stores a set of keys. No duplicate values are allowed.set DescriptionContainer Name CS 1410 - SJAllan Chapter 16 50 Iterators Can be used with cout to write information to an output device or a file.Output Can be used with cin to read information from an input device or a file.Input Can move forward and backward, and can jump to a specific data element in a container.Random-Access Can move forward or backward in a container (uses the ++ and -- operators).Bidirectional Can only move forward in a container (uses the ++ operator).Forward DescriptionIterator Type 26 CS 1410 - SJAllan Chapter 16 51 More on Iterators Iterators are associated with containers The type of container you have determines the type of iterator you use For example, vectors and deques require random-access iterators Lists, sets, multisets, maps, and multimaps require bidirectional iterators CS 1410 - SJAllan Chapter 16 52 Algorithms Algorithms are implemented as function templates They perform various operations on elements of containers They require algorithm header file Includes: binary_search, for_each, find_if, min_element, sort, count, find, max_element, random_shuffle and others 27 CS 1410 - SJAllan Chapter 16 53 Description of Some Algorithms Executes a function for each element of a container. For example, consider for_each(iter1, iter2, func); The statement calls the function func for each element in the range from iter1 to iter2, passing the element as the argument. for_each Returns the number of times a value appears in a range. For example, consider iter3 = count(iter1, iter2, value); The statements returns the number of times value is found in the range iter1 to iter2. count Performs a binary search for an object and returns true if the object is found. For example, consider binary_search(iter1, iter2, value); The statements performs a binary search in the range iter1 to iter2 looking for value binary_search DescriptionAlgorithm CS 1410 - SJAllan Chapter 16 54 Using find – Program #include <iostream> #include <vector> #include <algorithm> using namespace std; int main ( void ) { vector<int> numbers; vector<int>::iterator iter; for ( int x = 0; x < 10; x++ ) numbers.push_back( x ); cout << “The numbers in the vector are:\n”; for ( iter = numbers.begin( ); iter != numbers.end( ); iter++ ) cout << *iter << endl; cout << endl; iter = find( numbers.begin( ), numbers.end( ), 7 ); cout << *iter << endl; return 0; } // main
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved