Chapter 8 Writing Generic Functions. Objectives Understand the use of generic functions. Learn about the use of templates, their advantages and pitfalls.

Slides:



Advertisements
Similar presentations
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Advertisements

Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
Chapter 14: Overloading and Templates C++ Programming: Program Design Including Data Structures, Fifth Edition.
Chapter 10.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Chapter 9: Arrays and Strings
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
C++ for Engineers and Scientists Third Edition
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Chapter 8 Arrays and Strings
Chapter 15: Operator Overloading
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Data Structures Using C++ 2E
Chapter 6 Using Library Algorithms. Objectives Explore the use of predefined library functions that are designed to be used with sequential container.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Lists in Python.
Scott Marino MSMIS Kean University MSAS5104 Programming with Data Structures and Algorithms Week 10 Scott Marino.
Chapter 9 Defining New Types. Objectives Explore the use of member functions when creating a struct. Introduce some of the concepts behind object-oriented.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
Chapter 8 Arrays and Strings
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 16: Exceptions,
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
CPSC 252 Operator Overloading and Convert Constructors Page 1 Operator overloading We would like to assign an element to a vector or retrieve an element.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
Writing Generic Functions Lecture 20 Hartmut Kaiser
Pointers *, &, array similarities, functions, sizeof.
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
Arrays.
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Chapter 11 Defining Abstract Data Types. Objectives Learn how to use create objects that employ dynamic memory management. Explore creating objects that.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Function Templates 16.2.
Working with Batches of Data
Chapter VII: Arrays.
Exceptions, Templates, and the Standard Template Library (STL)
Collections Intro What is the STL? Templates, collections, & iterators
Strings, Line-by-line I/O, Functions, Call-by-Reference, Call-by-Value
ADT Implementations: Templates and Standard Containers
7 Arrays.
Abstraction: Generic Programming, pt. 2
Standard Version of Starting Out with C++, 4th Edition
Exceptions, Templates, and the Standard Template Library (STL)
COP 3330 Object-oriented Programming in C++
Presentation transcript:

Chapter 8 Writing Generic Functions

Objectives Understand the use of generic functions. Learn about the use of templates, their advantages and pitfalls. Examine the use of type parameters. Further investigate the theory and properties of iterators including the different types of iterators See how iterators can be used in input and output.

C++ Sometimes it pays to stay in bed on Monday, rather than spending the rest of the week debugging Monday's code. - Christopher Thompson Measuring programming progress by lines of code is like measuring aircraft building progress by weight. - Bill Gates Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - Brian W. Kernighan.

Generic Functions The functions we have created so far have specific parameter and return types. We have used library functions that could work on many different types. – The find function can find entries of any type in several different types of containers. The problem is this, how do we determine which types make sense for a particular function and which do not? – e.g. we can average ints, floats, doubles, complex numbers, etc. but what do we mean by an average string ?

Generic Functions The find function accepts two iterators and a value as parameters. We can used the function with different types of iterators, but they must be iterators. The important point here is that find uses operations that only iterators support so it doesn’t make sense to call it with other types of parameters.

Templates C++ uses a feature called templates to implement generic functions. We can write a single definition to create a family of functions (or types) that function similarly except for different template parameters. Objects of different types may share common behaviors. Template parameters let us write programs in terms of that common behavior.

Template Parameters We use a template parameter when we create a container type. vector The vector type and its associated functions work on different types of entries. We specify the type of the vector inside the angle brackets <>.

Medians Let’s create a median function that can calculate the median of vectors with other types besides double. The first step is to create a template header. template This indicates we are defining a template function and the function will use T as a type parameter. This is a variable that is used to specify a type. We will use the type parameter T to specify the types of other parameters and the return type.

Medians template T median(vector v) { typedef typename vector ::size_type vec_sz; vec_sz size = v.size(); if (size == 0) throw domain_error("median of an empty vector"); sort(v.begin(), v.end()); vec_sz mid = size/2; return size % 2 == 0 ? (v[mid] + v[mid-1]) / 2 : v[mid]; }

Medians We can use this function with any type of vector as long as the operations used are supported. – Sort – Addition – Division by 2 Suppose we create a vector of ints. vector x When we pass this vector to the median function it will use the type of the vector to determine the value for T. m = median(x) Since x is a vector we know that T is int.

Using Type Parameters We use the type parameter to specify the parameters types and the return type. T median(vector v) When we compile the code a specific version is created (instantiated) and will behave as if we had typed int in place of every T. This means we may end up with several different compiled versions of our function: one for ints, one for floats, etc.

typename We can create variables based on this type. typedef typename vector ::size_type vec_sz The reason we have the typename keyword here is that when we compile this code the computer may complain because vector is not yet a type and so doesn’t have a size_type attribute (yet). The problem is the vector class is not an integrated part of the compiler. The typename basically tell the the compiler “trust us, this will be a type eventually.”

Header Files Notice the compiler cannot completely compile a template function until it know the type. This implies we cannot do separate compilation. Instead of putting the declaration in the header file (.h ) and the code in a separate (.cc,.C,.cp,.cpp ) file we will put everything in the.h file. There will be a penalty in terms of compile time.

Problems with Types Be careful of the how types interact when using templates. find(s.homework.begin(), s.homework.end(), 0); This works with int, float and double because 0 automatically converts to 0.0. find(s.homework.begin(), s.homework.end(), 0.0); This won’t work with int because 0.0 does not convert to 0.

Problems with Types Still more problems. accumulate(v.begin(), v.end(), 0) This function creates an accumulator based on the type of the third argument. In this case it will work with float and double but the result will be truncated to an int. accumulate(v.begin(), v.end(), 0.0) This function works with int as well as float and double. The only potential problem is the return value will be a double.

Problems with Types Consider the following implementation of max. Template T max(const T& left, const T& right) { return left < right ? left : right; } Suppose we pass an int and a double. What is T ? Is it int or a double ? This is why the library max function insists its parameters must be exactly the same type.

Data Structure Independence Why do we need to specify all those iterators? find(c.begin(), c.end(), val) Why not just pass the structure and value? find(c, val) Or even use a method? c.find(val) There are three reasons. – Iterators allow us to find the value in part of a list. – The find function can work with any container. – Iterators can have special properties themselves rbegin marches backward through the structure.

Iterators and Algorithms Notice that some container classes support iterator operations that other do not. –it + 5 makes sense if it is an iterator to a vector but not if it is an iterator to a list. This means that some algorithms work with certain types of iterators but not others. –sort works for iterators to vectors but not for iterators to lists. There are five iterator categories that specify what operations and algorithms will work with them.

Sequential Read-Only Access These iterators are used to read the elements of a sequence and are called input iterators. Here input means getting data from the structure into the rest of our program. They must support the following operations. – Increment (pre and post) ( ++) – Equality comparison (==, !=) – Dereference (*, ->) All our iterators support these operations so they are all input iterators.

Sequential Write-Only Access We may need to use an iterator to write elements of a sequence, these are called output iterators. Notice the meaning of output and input are confusing when it comes to iterators! They must support the following operations. – Assignment ( *it = value ) – Increment (pre and post) (++) – The restriction that we cannot increment twice in a row without an assignment (skip an entry in our output to the structure). – The restriction that we cannot assign twice without an increment (overwrite an existing entry). All our iterators can be used this way. back_inserter enforces the restrictions.

Sequential Read-Write Access Some iterators can only be incremented but not decremented (we can only travel in one direction through the structure). These are called forward iterators. They support the following operations. – Dereferencing (*, ->) for both reading and writing. – Increment (pre and post) (++) – Equality comparison (==, !=) These iterators do not necessarily support decrement (--).

Reversible Access If we can move both backward and forward through the structure then it is a bidirectional iterator. It must support the forward operations in addition to the decrement operator (pre and post) (--). The standard-library container classes all support-bidirectional iterators.

Random Access Some functions need to jump around in a container. Many sorting and searching algorithms need iterators that can jump. Iterators that support this are random-access. We need to be able to do arithmetic on our iterators so there are additional required operations. – Arithmetic between an integer n and an iterator p ( p + n, p - n, n + p ) – Arithmetic between iterators p and q ( p – q ) – Indexing ( p[n] which is equivalent to *(p + n) ) – Comparison ( p q, p = q ) Only vector and string iterators are random-access.

Off-the-end Iterators Why does end() produce an iterator that is one past the last entry in the structure? There are several reasons. – It is easier to write loops that run through the entire structure and do not need to treat the last element as special. –end() makes sense even for empty lists. – For all but random-access iterators we only need to compare iterators for equality (==, !=). You don’t need to check for <= end. – It gives us a natural return value when a function fails. What should find(c.begin(), c.end(), 0) return if there are no 0’s in the structure?

Input and Output Iterators All our standard-library containers support are input, output and forward iterators. Not all iterators fall into all three categories. –back_inserter is an output only iterator. Iterators can be associate with things other than containers. – Iterators for istream are input iterators. – Iterators for ostream are output iterators.

Input Stream Iterator With an input stream iterator we can read from input and store the results in a container using the standard copy function. copy(istream_iterator (cin), istream_iterator (), back_inserter(v)) This actually creates a beginning iterator bound to the the input stream cin. Notice we need to specify the type to read when we create the iterators. The ending iterator is a default iterator. This will be the value that will result when we reach end-of-file or some other error state.

Output Stream Iterators We can also use iterators to copy a container to output. copy(v.begin(), v.end(), ostream_iterator (cout, “ “)); Notice that the ostream_iterator will be used to send int values to cout and they will be separated by spaces. The following would print without any spaces. copy(v.begin(), v.end(), ostream_iterator (cout));

Split Revisited We can make an improvement to our split function. Instead of returning a vector of strings, we will return any type of container that can hold strings. The function will now accept an output iterator instead of returning a value. We will write the words we find to the structure associated with this iterator (whatever that is).

Split Revisited template // changed void split(const string& str, Out os) { // changed typedef string::const_iterator iter; iter i = str.begin(); while (i != str.end()) { i = find_if(i, str.end(), not_space); iter j = find_if(i, str.end(), space); if (i != str.end()) *os++ = string(i, j); // changed i = j; } }

Split Revisited The type of the iterator os is used to define the type parameter Out. We only use the iterator os in one place. *os++ = string(i, j); So we only need the operations of increment (++) and dereferencing for assignment ( *it = ). We can use an output iterator with this function.

Using Split We could use split to put the resulting words in any appropriate container. split(s, back_inserter(word_list)); We could also use split to send the results to output. int main() { string s; while (getline(cin, s)) split(s, ostream_iterator (cout, "\n")); return 0; }

Templates for Functions without Arguments If we have a function that does not have an argument list we can still use templates. template T zero() { return 0; } To call this function we need to supply the turn type. double x = zero ();

Homework Chapter 8 (page 154) Total 45 pts possible. – 8-0 – 8-2 (equal, find, find_if, copy, transform) ( , 10 pts each) – 8-4 (paper, 10 pts) – 8-7 (paper, 5 pts) – 8-8 (paper, 5 pts)