Chapter 16 – Exceptions, Templates, and the Standard Template

Download Report

Transcript Chapter 16 – Exceptions, Templates, and the Standard Template

Chapter 16 – Exceptions, Templates, and the
Standard Template Library (STL)
• Exceptions are used to signal errors or
unexpected events that occur while a
program is running.
• We have checked for errors before by
placing if statements that checked for the
condition or by using assert statements.
1
Starting Out with C++, 3rd Edition
Exceptions (cont)
• An exceptional condition is a value or an
object that signals an error.
• When the error occurs, an exception is
“thrown.”
2
Starting Out with C++, 3rd Edition
Throwing an Exception
Rational::Rational ( int numerator, int
denominator )
{ if ( denominator == 0 )
throw "ERROR: Cannot divide by
zero.\n";
this->numerator = numerator;
this->denominator = denominator;
} // divide
3
Starting Out with C++, 3rd Edition
Throw
• The line containing a throw statement is
called the throw point.
• When a throw statement is executed, control
is passed to an exception handler.
• When an exception is thrown by a function,
the function aborts.
• Any type can be “thrown”
4
Starting Out with C++, 3rd Edition
Handling an Exception
• An exception is handled by a try/catch
construct.
• The try block contains a block of code that
may directly or indirectly cause an
exception to be thrown.
• The catch block contains a block of code
that handles the exception.
5
Starting Out with C++, 3rd Edition
Example Exception Handler
try
{
Rational q = Rational( num1, num2 );
cout << q << endl;
} // try
catch ( char *exceptionString )
{
cout << exceptionString;
} // catch
6
Starting Out with C++, 3rd Edition
Handling an Exception (cont)
• If divide throws an exception, the exception is
caught by the catch statement.
• The type of the parameter to the catch statement
must be the same as in the throw statement (or
class from which it is derived).
• Execution continues after the try/catch statement,
unless the catch statement does something else.
7
Starting Out with C++, 3rd Edition
Uncaught Exceptions
•
Ways for uncaught exceptions:
– No catch statement with a parameter of the
correct data type.
– The exception is thrown outside a try
statement.
•
In either case, the exception causes the
program to abort.
8
Starting Out with C++, 3rd Edition
More on Exceptions
• Exceptions can be put in classes. This
allows us to do more with them.
• We can have multiple exception classes.
• Exception classes can have parameters that
allow information to be returned.
9
Starting Out with C++, 3rd Edition
IntMain.cpp – Program (cont)
in getInput…
throw OutOfRange( input );
in main…
try
{ userValue = range.getInput();
cout << "You entered " << uservalue << endl;
} // try
catch ( IntRange::OutOfRange ex )
{ cout << "That value " << ex.value
<< " is out of range." << endl;
} // catch
cout << "End of program." << endl;
} // main
10
Starting Out with C++, 3rd Edition
Class for exceptions
class BadTrait{
private:
string msg;
public:
BadTrait(string errorMsg, int val){
char str[10];
itoa(val,str,10); // integer, string to convert to, number sys
msg = errorMsg+str;
}
string getMsg(){ return msg;}
};
11
Starting Out with C++, 3rd Edition
How to Throw
// add newEle to set only if it is a legal element
Set &Set::operator+=(int newEle){
if (newEle <memberMax && newEle >=0)
member[newEle]=true;
else throw BadTrait("Error: Adding element which
is out of range " , newEle);
return *this;
}
12
Starting Out with C++, 3rd Edition
How to catch
try{
Traits me;
me+=4; me += 5;me +=11; me +=27;
}catch (BadTrait b){
cout<< b.getMsg() << endl;}
13
Starting Out with C++, 3rd Edition
Unwinding the Stack
• When an exception is thrown, the function
immediately terminates.
• If that function was called by another
function, then the calling function
terminates as well.
• This process continues.
• This is called unwinding the stack.
14
Starting Out with C++, 3rd Edition
Dynamic Arrays
Suppose I wanted an array that changed in
size.
How would I implement that?
What operations would I expect to have?
Starting Out with C++, 3rd Edition
Magic Genie
Give me what I want.
Would I have any concerns?
Starting Out with C++, 3rd Edition
Introduction to the Standard Template
Library (STL)
• The Standard Template Library contains
many templates for useful algorithms and
data structures.
• template: a stencil, pattern or overlay used
in graphic arts
• Is a template complete?
• The Magic Genie
17
Starting Out with C++, 3rd Edition
Abstract Data Types
– what is an abstract data type?
• The most important data structures in STL
are containers and iterators:
– Container – a class that stores data and
organizes it in some fashion.
– Iterator – similar to a pointer and is used to
access the individual data elements in a
container.
Why do we need iterators at all?
18
Starting Out with C++, 3rd Edition
Container Classes
• Sequence – organizes data in a sequential
fashion similar to an array.
“Give me item 7”
• Associative – uses keys to rapidly access
elements in the data structure.
“Give me the scissors”
19
Starting Out with C++, 3rd Edition
Sequence Containers – Has an order
Container Name
vector
deque
list
Description
An expandable array. Values may be added to
or removed from the end (push back)
or middle (insert).
Like a vector, but also allows values to be added
to or removed from the front.
A doubly-linked list of data elements. Values
may be inserted in or removed from any
position.
They differ in the underlying representation.
20
Starting Out with C++, 3rd Edition
Weak Sauce Genie
Makes you give him more
information. “What are you
going to do with it?”
Which is better for racing - a
general purpose bike or a
racing bike?
This genie has an attitude. He
doesn’t give it the way you
want it, but just the way he
wants.
Starting Out with C++, 3rd Edition
Associative Containers – stored by value
Container Name Description
set
Stores a set of keys. No duplicate values are
allowed.
multiset
Stores a set of keys. Duplicates are allowed.
map
Maps a set of keys to data elements. Only
one key per data element is allowed.
Duplicates are not allowed.
multimap
Maps a set of keys to data elements. Many
keys per data element are allowed.
Duplicates are allowed.
22
Starting Out with C++, 3rd Edition
So how do associative containers work?
Come back next semester…
Starting Out with C++, 3rd Edition
Using Vectors – Program
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void doubleValue ( int &val )
{ val *= 2;
} // doubleValue
void main ( void )
{ vector<int> numbers;
vector<int>::iterator iter; // Notice scope resolution operator ::
24
Starting Out with C++, 3rd Edition
Using Vectors – Program (cont)
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;
for_each ( numbers.begin(), numbers.end(), doubleValue );
cout << “The numbers again are:\n”;
for ( iter = numbers.begin(); iter != numbers.end(); iter++ )
cout << *iter << endl;
cout << endl;
} // main
25
Starting Out with C++, 3rd Edition
“for each” acts like…
for_each(Iterator first, Iterator last, Function f)
for ( ; first!=last; ++first )
f(*first);
Starting Out with C++, 3rd Edition
Visit with your neighbor
Create a vector of strings.
Add the lines of your favorite poem to the
vector.
Print them out assuming you really can’t
remember how many lines you put in.
Starting Out with C++, 3rd Edition
Visit with your neighbor
Create a vector of integers.
Put in multiples of 5.
Print them out, backwards USING
ITERATORS.
Starting Out with C++, 3rd Edition
What do you think this does?
const int SIZE=5;
vector<vector<int> > items ( SIZE, vector<int> ( SIZE ) );
for (int i=0; i < SIZE; i++)
for (int j=0; j < SIZE; j++)
items[i][j]=i+j;
for(int ii=0; ii < SIZE; ii++)
{
for(int jj=0; jj < SIZE; jj++)
{
cout << items[ii][jj] << " ";
}
cout << endl;
}
Starting Out with C++, 3rd Edition
What do you think this does?
int k=0;
vector<vector<int> > things ;
for (int i=0; i < SIZE; i++)
{ things.push_back(vector<int>());
for (int j=0; j < SIZE; j++)
things[i].push_back(k++);
}
for(int ii=0; ii < SIZE; ii++)
{
for(int jj=0; jj < SIZE; jj++)
{
cout << setw(3) << things[ii][jj] << " ";
}
cout << endl;
}
Starting Out with C++, 3rd Edition
What do you think this does?
int num_of_col = 5;
int num_of_row = 9;
const char TREE = 'T';
const char BURNING = '*';
const char EMPTY = ' ';
vector< vector<char> > forest;
//now we have an empty 2D-matrix of size (0,0). Resizing it with one single command
forest.resize( num_of_row , vector<char>( num_of_col , TREE ) );
for(int ii=0; ii < num_of_row; ii++)
{
for(int jj=0; jj < num_of_col; jj++)
{
cout << forest[ii][jj] ;
}
cout << endl;
}
Starting Out with C++, 3rd Edition
Function Templates
• A function template is a “generic” function
that can work with any data type.
• The programmer writes the specifications of
the function, but substitutes parameters for
data types.
• Given the examples we did for vectors. Can
you think of a generic function we may want?
32
Starting Out with C++, 3rd Edition
• When the compiler encounters a call to
the function, it generates code to handle
the specific data type(s) used in the call.
We call this inefficient, right?
This is not like inheritance.
Tell me the difference.
Starting Out with C++, 3rd Edition
Template Example
• We want a function that prints out the
values of an array.
• This function should work with arrays of
type int, float, char, or string.
• In a perfect world (where all these types
descended from the same base type), we
could use inheritance to make this happen.
34
Starting Out with C++, 3rd Edition
First, do it for one type – at your seats
We want a function that prints out the values
of an array.
Let’s print out values ten to a line.
Starting Out with C++, 3rd Edition
printArray.cpp – Program
#include <iostream>
#include <string>
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
36
Starting Out with C++, 3rd Edition
printArray.cpp – Program (cont)
void main ( void )
{ const int aSize = 5, bSize = 7, cSize = 6, dSize = 3;
int a[ aSize ] = { 1, 2, 3, 4, 5 };
float b[ bSize ] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char c[ cSize ] = "Hello";
string d[ dSize ] = { "I", "love", "CS" };
printArray(
printArray(
printArray(
printArray(
} // main
a, aSize );
b, bSize );
c, cSize );
d, dSize );
37
Starting Out with C++, 3rd Edition
Generic swap
• Suppose we wanted a generic
swap.
First do it for one type – at your seats.
38
Starting Out with C++, 3rd Edition
Generic swap
• Suppose we wanted a generic swap.
template <class T>
void swap ( T &var1, T &var2 )
{ T temp;
temp = var1;
var1 = var2;
var2 = temp;
} // swap
39
Starting Out with C++, 3rd Edition
Suppose we wanted a generic Max
function
Try it at your seats
Starting Out with C++, 3rd Edition
Suppose we want a generic Max function
template <class T>
T maximum(T a, T b)
{
return a > b ? a : b ; // Familiar operator?
}
void main()
{ cout << "max(10, 15) = " << maximum(10, 15) << endl ;
cout << "max('k', 's') = " << maximum('k', 's') << endl ;
cout << "max(10.1, 15.2) = " << maximum(10.1, 15.2) << endl ;
}
Starting Out with C++, 3rd Edition
Template with Multiple Types
template <class T1, class T2>
void swap ( T1 &var1, T2 &var2 )
{ T1 temp;
temp = var1;
var1 = (T1)var2;
var2 = (T2)temp;
} // swap
42
Starting Out with C++, 3rd Edition
Operators in Template
• If arithmetic or relational operators are used
in templates, they must be defined for the
different types of the templates actually
passed in.
• If the operators are not defined for a
particular type, the compiler generates an
error.
43
Starting Out with C++, 3rd Edition
Class Templates
• Templates may also be used to create
generic classes and abstract data types.
• Class templates allow you to create one
general version of a class without having to
duplicate code to handle multiple data
types.
44
Starting Out with C++, 3rd Edition
Generic Class
• Suppose you wanted to have a class that
held a collection of objects.
• We want this class to work with different
data types.
• We could create a different class for each
data type, but there is a better solution.
• We will look at a class template.
45
Starting Out with C++, 3rd Edition
SimpleVector.h – Program
template <class T>
class SimpleVector
{ private:
T *v;
int arraySize;
public:
SimpleVector ( void ) { v = NULL; arraySize = 0; } ;
SimpleVector ( int );
SimpleVector ( const SimpleVector & );
~SimpleVector ( void );
int getSize ( void ) { return arraySize; };
T &operator[] ( const int & );
}; // SimpleVector
46
Starting Out with C++, 3rd Edition
SimpleVector.cpp – Program
template <class T>
SimpleVector<T>::SimpleVector ( int s )
{ arraySize = s;
v = new T [ s ];
assert( v);
for ( int i = 0; i < arraySize; i++ )
v[i]= 0;
} // SimpleVector::SimpleVector
template <class T>
SimpleVector<T>::~SimpleVector ( void )
{ if ( arraySize > 0 )
delete [] v;
} // SimpleVector::~SimpleVector
void main()
{
SimpleVector<int> mine(5);
cout << mine.getSize() << endl;
}
47
Starting Out with C++, 3rd Edition
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.
48
Starting Out with C++, 3rd Edition
At your seats
Try adding a new function to print out the
contents of the simple vector
Starting Out with C++, 3rd Edition
void printAll(void);
template <class T>
void SimpleVector<T>::printAll(void)
{ cout << "contents:";
for (int i=0 ;i < arraySize; i++)
cout << v[i] << " ";
cout << endl;
}
Starting Out with C++, 3rd Edition
Class Templates and Inheritance
#ifndef SEARCHABLEVECTOR_H
#define SEARCHABLEVECTOR_H
#include “SimpleVector.h”
template <class T>
class SearchableVector : public SimpleVector<T>
{ public:
SearchableVector ( ) : SimpleVector<T>( ) { }
SearchableVector ( int s ) : SimpleVector<T>( s ) { }
SearchableVector ( SearchableVector & );
int findItem ( T );
}; // SearchableVector
51
Starting Out with C++, 3rd Edition