Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.

Similar presentations


Presentation on theme: "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy."— Presentation transcript:

1 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)

2 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Topics 16.1 Exceptions 16.2 Function Templates 16.3 Class Templates 16.4 Class Templates and Inheritance 16.5 Introduction to the Standard Template Library 16-2

3 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16.1 Exceptions An exception is a condition that occurs at execution time and makes normal continuation of the program impossible When an exception occurs, the program must either terminate or jump to special code for handling the exception. The special code for handling the exception is called an exception handler 16-3

4 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 4 Exceptions Indicate that something unexpected has occurred or been detected Allow program to deal with the problem in a controlled manner Can be as simple or complex as program design requires The line containing the throw statement is the throw point –Control is passed to another part of the program known as the exception handler –When an exception is thrown by a function, the function aborts

5 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions – Key Words Exception: object or value that signals an error Throw an exception: send a signal that an error has occurred –throw – followed by an argument, is used to throw an exception Catch/Handle an exception: process the exception; interpret the signal –try – followed by a block { }, is used to invoke code that throws an exception –catch – followed by a block { }, is used to detect and process exceptions thrown in preceding try block. Takes a parameter that matches the type thrown. 16-5

6 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 6 Coding for Exceptions int main() { int numerator[3]={10,0,10}; int denominator[3]= {2,10,0}; double answer; for (int i=0; i<3;i++) { answer = divide(numerator[i], denominator[i]); cout<<numerator[i]<<" divided by "<<denominator[i] <<" = "<<answer<<endl; } cout<<endl<<endl; for (int i=0; i<3;i++) { answer = divide_throw(numerator[i], denominator[i]); cout<<numerator[i]<<" divided by "<<denominator[i]<<" = "<<answer<<endl; } return 0; }

7 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 7 Coding for Exceptions double divide(int n, int d) { if (d==0) { cout<<"ERROR: Cannot divide by zero "; return 0; } else return static_cast (n)/d; } double divide_throw(int n, int d) { if (d==0) { throw "ERROR: Cannot divide by zero\n"; } else return static_cast (n)/d; }

8 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 8 Coding for Exceptions - Output Output from function divide 10 divided by 2 = 5 0 divided by 10 = 0 ERROR: Cannot divide by zero 10 divided by 0 = 0 Output from function divide_throw 10 divided by 2 = 5 0 divided by 10 = 0 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

9 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Throwing an Exception Code that detects the exception must pass information to the exception handler. This is done using a throw statement: throw "Emergency!" throw 12; In C++, information thrown by the throw statement may be a value of any type 16-9

10 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Catching an Exception Block of code that handles the exception is said to catch the exception and is called an exception handler An exception handler is written to catch exceptions of a given type: For example, the code catch(char *str) { cout << str; } can only catch exceptions of C-string type 16-10

11 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Catching an Exception Another example of a handler: catch(int x) { cerr << "Error: " << x; } This can catch exceptions of type int 16-11

12 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Connecting to the Handler Every catch block is attached to a try block of code and is responsible for handling exceptions thrown from that block try { } catch(char e1) { // This code handles exceptions // of type char that are thrown // in this block } 16-12

13 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Execution of Catch Blocks The catch block syntax is similar to a that of a function Catch block has a formal parameter that is initialized to the value of the thrown exception before the block is executed 16-13

14 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 14 Exceptions – Flow of Control 1)A function that throws an exception is called from within a try block 2)If the function throws an exception, the function terminates and the try block is immediately exited. 1)A catch block to process the exception is searched for in the source code immediately following the try block. 2)If a catch block is found that matches the exception thrown, it is executed. 3)If no catch block that matches the exception is found, the program terminates.

15 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 15

16 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 16 THIS WORKS in Code::Blocks char* msg; msg = "ERROR: Cannot divide by zero.\n"; if (denominator == 0) throw msg;

17 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 17 What Happens in the Try/Catch Construct

18 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exception Example An example of exception handling is code that computes the square root of a number. It throws an exception in the form of a C- string if the user enters a negative number 16-18

19 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example int main( ) { try { double x; cout << "Enter a number: "; cin >> x; if (x < 0) throw "Bad argument!"; cout << "Square root of " << x << " is " << sqrt(x); } catch(char *str) { cout << str; } return 0; } 16-19

20 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Flow of Control 1.Computer encounters a throw statement in a try block 2.The computer evaluates the throw expression, and immediately exits the try block 3.The computer selects an attached catch block that matches the type of the thrown value, places the value in the catch block’s formal parameter, and executes the catch block 16-20

21 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 21 What if no exception is thrown?

22 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 22 Catch Exception and Reprompt int main() { int num1, num2; // To hold two numbers double quotient; // To hold the quotient of the numbers bool goodResult; //test if no exception thrown do{ cout << "Enter two numbers: "; cin >> num1 >> num2; goodResult=true; try { quotient = divide(num1, num2); cout << "The quotient is " << quotient << endl; } catch (char *exceptionString) { goodResult=false; cout <<exceptionString; } } while (!goodResult); cout << "End of the program.\n"; return 0; }

23 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 23 Exceptions - Notes An integer can be thrown to signal a predefined error code try { quotient = divide(num1, num2); cout << "The quotient is " << quotient << endl; } catch (int exceptionInt) { goodResult=false; cout <<“Error code”<<exceptionInt; } In the function write: if (denominator == 0) throw 333; and then look up the code in a library or table

24 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Uncaught Exception An exception may be uncaught if –there is no catch block with a data type that matches the exception that was thrown, or –it was not thrown from within a try block The program will terminate in either case 16-24

25 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Handling Multiple Exceptions Multiple catch blocks can be attached to the same block of code. The catch blocks should handle exceptions of different types try{...} catch(int iEx){ } catch(char *strEx){ } catch(double dEx){ } 16-25

26 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Throwing an Exception Class An exception class can be defined and thrown Catch block must be designed to catch an object of the exception class Exception class object can pass data to exception handler via data members An exception class may have: –no members: used only to signal an error –members: pass error data to catch block A class can have more than one exception class 16-26

27 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 27 Exception class definition

28 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 28

29 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 29

30 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 30 Program Output

31 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 31 Handling Multiple Exceptions To differentiate between a negative width and length, two classes can be created and each called based on the type of error In Rectangle.h include: public: class NegativeWidth { }; // Exception class for a negative width class NegativeLength { }; // Exception class for a negative length and in main change the try blocks to the following: try { myRectangle.setWidth(width); myRectangle.setLength(length); cout << "The area of the rectangle is “ << myRectangle.getArea() << endl; } catch (Rectangle::NegativeWidth) { cout<<"Error: A negative value was given "<< "for the rectangle's width.\n"; } catch (Rectangle::NegativeLength) { cout<<"Error:A negative value was given "<< "for the rectangle's length.\n"; }

32 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 32 Recovering From Exceptions Within the catch block, prompt the user to re- enter the correct length or width // Get the rectangle's width. cout << "Enter the rectangle's width: "; cin >> width; // Store the width in the myRectangle object. while (tryAgain) { try { myRectangle.setWidth(width); // If no exception was thrown, then the // next statement will execute. tryAgain = false; } catch (Rectangle::NegativeWidth) { cout << "Please enter a non-negative width: "; cin >> width; } // Get the rectangle's length. cout << "Enter the rectangle's length: "; cin >> length; // Store the length in the myRectangle object. tryAgain = true; while (tryAgain) { try { myRectangle.setLength(length); // If no exception was thrown, then the // next statement will execute. tryAgain = false; } catch (Rectangle::NegativeLength) { cout << "Please enter a non-negative length: "; cin >> length; }

33 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 33 Recovering From Exceptions Enter the rectangle's width: -4 Please enter a non-negative width: -6 Please enter a non-negative width: 6 Enter the rectangle's length: -9 Please enter a non-negative length: 9 The rectangle's area is 54

34 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 34 Extracting Data from the Exception Class Sometimes, we want an exception object to pass data back to the exception handler –We want the Rectangle class not only to signal when a negative value was entered, but to pass back that value as well –This can be accomplished by expanding the exception class with members in which data can be stored. For example: class NegativeWidth { private: int value; public: NegativeWidth(int val) { value = val; } int getValue() const { return value; } }; Which is thrown by throw NegativeWidth(w); And caught by: catch (Rectangle::NegativeWidth e) { cout<< "Error: "<<e.getValue()<< " is an invalid value for the" <<" rectangle's width.\n"; }

35 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 35 What Happens After catch Block? Once an exception is thrown, the program cannot return to throw point. The function executing throw terminates (does not return), other calling functions in try block terminate, resulting in unwinding the stack If an exception is thrown by the member function of a class object, then the class destructor is called If objects were created in the try block and an exception is thrown, they are destroyed.

36 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 36 Nested try Blocks try/catch blocks can occur within an enclosing try block Exceptions caught at an inner level can be passed up to a catch block at an outer level: catch ( ) {... throw; // pass exception up } // to next level

37 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 37 Nested try Blocks #include using namespace std; void doA(); void doB(); int main() { char *exception1; try{ doA(); } catch(char *exception1) { cout<<"Exception 1 handled in main"<<endl; } return 0; } void doA(){ char *exception1; try{ doB(); } catch(char *exception1) { cout<<"Exception 1 in doA(),rethrown“ <<endl; throw; } void doB(){ char *exception1; try{ throw exception1; } catch(char *exception1) { cout<<"Exception 1 in doB(),rethrown“ <<endl; throw; } Exception 1 in doB(),rethrown Exception 1 in doA(),rethrown Exception 1 in main, handled in main

38 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exception When Calling new If new cannot allocate memory, it throws an exception of type bad_alloc Must #include to use bad_alloc Can invoke new from within a try block, use a catch block to detect that memory was not allocated. 16-38

39 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 39 Handling the bad_alloc Exception When the new operator is unable to allocate the requested amount of memory, a bad_alloc exception is thrown. It can be handled as follows:

40 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16.2 Function Templates Function template: A pattern for creating definitions of functions that differ only in the type of data they manipulate Better than overloaded functions, since the code defining the algorithm of the function is only written once 16-40

41 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 41 Function Templates Function template: a generic function that can work with any data type. –It is a template and by itself does not cause memory to be used –An actual instance of the function is created in memory when the compiler encounters a call to the template function The programmer writes the specifications of the function, but substitutes parameters for data types When called, compiler generates code for specific data types in function call

42 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 42 Function Template Example template T square(T num) { return num * num; } template prefix generic data type type parameter What gets generated when square is called with an int: What gets generated when square is called with a double: int square(int num) { return num * num; } double square(double num) { return num * num; }

43 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 43 Function Template Example template T square(T num) { return num * num; } Call a template function in the usual manner: int ival = 3; double dval = 12.5; cout << square(ival); // displays 9 cout << square(dval); // displays 156.25 See projectTemplateSquareFunction

44 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 44 Function Template Swap Example #include using namespace std; template void swapVars(T &var1, T &var2) { T temp; temp = var1; var1 = var2; var2 = temp; }

45 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 45 Function Template Swap Example int main() { char firstChar, secondChar; // Two chars int firstInt, secondInt; // Two ints double firstDouble, secondDouble; // Two doubles // Get and swapVars two chars cout << "Enter two characters: "; cin >> firstChar >> secondChar; swapVars(firstChar, secondChar); cout << firstChar << " " << secondChar << endl; // Get and swapVars two ints cout << "Enter two integers: "; cin >> firstInt >> secondInt; swapVars(firstInt, secondInt); cout << firstInt << " " << secondInt << endl; // Get and swapVars two doubles cout << "Enter two floating-point numbers: "; cin >> firstDouble >> secondDouble; swapVars(firstDouble, secondDouble); cout << firstDouble << " " << secondDouble << endl; return 0; }

46 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A swap Template The logic of both functions can be captured with one template function definition template void swap(T &x, T &y) { T temp = x; x = y; y = temp; } 16-46

47 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using a Template Function When a function defined by a template is called, the compiler creates the actual definition from the template by inferring the type of the type parameters from the arguments in the call: int i = 1, j = 2; swap(i,j); This code makes the compiler instantiate the template with type int in place of the type parameter T See project TemplateSwap 16-47

48 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Template Notes 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 referred to in the template are defined or overloaded in the class definition 16-48

49 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Template Notes All data types specified in template prefix must be used in template definition Function calls must pass parameters for all data types specified in the template prefix Function templates can be overloaded – need different parameter lists Like regular functions, function templates must be defined before being called 16-49

50 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Where to Start When Defining Templates Templates are often appropriate for multiple functions that perform the same task with different parameter data types Develop function using usual data types first, then convert 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 16-50

51 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 51 Function Template Notes Can define a template to use multiple data types: template Example: template // T1 and T2 will be replaced in the called function //with the data types of the arguments double mpg(T1 miles, T2 gallons) {return miles / gallons}

52 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 52 Function Template Notes #include using namespace std; template int largest(const T1 &var1, T2 &var2) { if (sizeof(var1) > sizeof(var2)) return sizeof(var1); else return sizeof(var2); } int main() { int i = 0; char c = ' '; float f = 0.0; double d = 0.0; cout << "Comparing an int and a double, the largest\n" << "of the two is " << largest(i, d) << " bytes.\n"; cout << "Comparing an char and a float, the largest\n" << "of the two is " << largest(c, f) << " bytes.\n"; return 0; } Comparing an int and double, the largest of the two is 8 bytes Comparing a char and a float, the largest of the two is 4 bytes

53 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 53 Function Template Notes Function templates can be overloaded Each template must have a unique parameter list template T sum(T val1, T val2) {return val1 + val2} template T sum(T val1, T val2, T val3) {return val1 + val2 + val3} See project TemplateOverload

54 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 54 Defining Your Own Templates Templates are often appropriate for multiple functions that perform the same task with different parameter data types Develop function using usual data types first, then convert to a template: –add template prefix template –convert data type names in the function to a type parameter (i.e., a T type) in the template

55 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16.3 Class Templates Classes can also be represented by templates. When a class object is created, type information is supplied to define the type of data members of the class. Unlike functions, a class template is instantiated by supplying the type name ( int, float, string, etc.) at object definition 16-55

56 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 56 Class Template Example template class grade { private: T score; public: grade(T); void setGrade(T); T getGrade() };

57 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 57 Class Template Example Pass type information to class template when defining objects: grade testList[20]; grade quizList[20]; Use as ordinary objects once defined

58 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Exceptions, Templates and STL 58 #include using namespace std; template class Grade { private: T score; public: Grade(T); void setGrade(T); T getGrade(); }; template Grade ::Grade(T s) { score = s; } template void Grade :: setGrade(T s) { score = s; } template T Grade :: getGrade() { return score; } int main() { Grade testlist[20]; testlist[0].setGrade(98); testlist[1].setGrade(85); testlist[2].setGrade(93); for (int i=0; i<3; i++) cout<<testlist[i].getGrade()<<" "; return 0; }

59 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Class Template Consider the following classes 1.Class used to join two integers by adding them: class Joiner { public: int combine(int x, int y) {return x + y;} }; 2.Class used to join two strings by concatenating them: class Joiner { public: string combine(string x, string y) {return x + y;} }; 16-59

60 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example class Template A single class template can capture the logic of both classes: it is written with a template prefix that specifies the data type parameters: template class Joiner { public: T combine(T x, T y) {return x + y;} }; 16-60

61 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using Class Templates To create an object of a class defined by a template, specify the actual parameters for the formal data types Joiner jd; Joiner sd; cout << jd.combine(3.0, 5.0); cout << sd.combine("Hi ", "Ho"); Prints 8.0 and Hi Ho See project TemplateClassJoiner 16-61

62 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16.4 Class Templates and Inheritance Templates can be combined with inheritance You can derive –Non template classes from a template class: instantiate the base class template and then inherit from it –Template class from a template class See project TemplatesInheritance 16-62

63 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16.5 Introduction to the Standard Template Library Standard Template Library (STL): a library containing templates for frequently used data structures and algorithms Programs can be developed faster and are more portable if they use templates from the STL 16-63

64 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Standard Template Library Two important types of data structures in the STL: –containers: classes that store data and impose some organization on it –iterators: like pointers; provides mechanisms for accessing elements in a container 16-64

65 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Containers Two types of container classes in STL: –sequential containers: organize and access data sequentially, as in an array. These include vector, dequeue, and list containers. Sequential containers have a front and back and can provide random access by specifying a position 16-65

66 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Containers –associative containers: use keys to allow data elements to be quickly accessed. These include set, multiset, map, and multimap containers. A telephone book uses name as the key in order to lookup the phone number 16-66

67 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Creating Container Objects To create a list of int, write list mylist; To create a vector of string objects, write vector myvector; Requires the vector header file See project VectorSTL 16-67

68 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Iterators Generalization of pointers, used to access information in containers Four types: –forward (uses ++ ) –bidirectional (uses ++ and -- ) –random-access –input (can be used with cin and istream objects) –output (can be used with cout and ostream objects) 16-68

69 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Containers and Iterators Each container class defines an iterator type, used to access its contents The type of an iterator is determined by the type of the container: list ::iterator x; list ::iterator y; x is an iterator for a container of type list 16-69

70 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Containers and Iterators Each container class defines functions that return iterators: begin(): returns iterator to item at start end(): returns iterator denoting end of container 16-70

71 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Containers and Iterators Iterators support pointer-like operations: if iter is an iterator: –*iter is the item it points to: this dereferences the iterator –iter++ advances to the next item in the container –iter-- backs up in the container The end() iterator points to past the end: it should never be dereferenced 16-71

72 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Traversing a Container Given a vector: vector v; for (int k=1; k<= 5; k++) v.push_back(k*k); Traverse it using iterators: vector ::iterator iter = v.begin(); while (iter != v.end()) { cout << *iter << " "; iter++} Prints 1 4 9 16 25 16-72

73 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member functions of the Vector class 16-73

74 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member functions of the Vector class 16-74

75 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member functions of the Vector class 16-75

76 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Member functions of the Vector class 16-76

77 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Algorithms STL contains algorithms implemented as function templates to perform operations on containers. Requires algorithm header file Collection of algorithms includes 16-77 binary_searchcount for_eachfind max_elementmin_element random_shufflesort and others

78 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using STL algorithms Many STL algorithms manipulate portions of STL containers specified by a begin and end iterator max_element(iter1, iter2) finds max element in the portion of a container delimited by iter1, iter2 min_element(iter1, iter2) is similar to above 16-78

79 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More STL algorithms random_shuffle(iter1, iter2) randomly reorders the portion of the container in the given range sort(iter1, iter2) sorts the portion of the container specified by the given range 16-79

80 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley random-shuffle Example The following example stores the squares 1, 4, 9, 16, 25 in a vector, shuffles the vector, and then prints it out 16-80

81 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley random_shuffle example int main() { vector vec; for (int k = 1; k <= 5; k++) vec.push_back(k*k); random_shuffle(vec.begin(),vec.end()); vector ::iterator p = vec.begin(); while (p != vec.end()) { cout << *p << " "; p++; } return 0; } 16-81

82 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)


Download ppt "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy."

Similar presentations


Ads by Google