G52CPP C++ Programming Lecture 18

Similar documents
G52CPP C++ Programming Lecture 18. Dr Jason Atkin

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

G52CPP C++ Programming Lecture 17

G52CPP C++ Programming Lecture 15

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

Introduction to C++ (Extensions to C)

G52CPP C++ Programming Lecture 20

Introduction to C++ Systems Programming

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

C++ basics Getting started with, and Data Types.

Topics. bool and string types input/output library functions comments memory allocation templates classes

Fast Introduction to Object Oriented Programming and C++

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

CS197c: Programming in C++

CS3157: Advanced Programming. Outline

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

W3101: Programming Languages C++ Ramana Isukapalli

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

1. The term STL stands for?

Chapter 15 - C++ As A "Better C"

Module 9. Templates & STL

CE221 Programming in C++ Part 1 Introduction

This is a CLOSED-BOOK-CLOSED-NOTES exam consisting of five (5) questions. Write your answer in the answer booklet provided. 1. OO concepts (5 points)

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Interview Questions of C++

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Lambda functions. Zoltán Porkoláb: C++11/14 1

Exceptions, Templates, and the STL

AN OVERVIEW OF C++ 1

Cours de C++ Introduction

File I/O Christian Schumacher, Info1 D-MAVT 2013

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

CSI33 Data Structures

More on Templates. Shahram Rahatlou. Corso di Programmazione++

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

use static size for this buffer

Short Notes of CS201

Logistics. Templates. Plan for today. Logistics. A quick intro to Templates. A quick intro to Templates. Project. Questions? Introduction to Templates

CS201 - Introduction to Programming Glossary By

COEN244: Class & function templates

G52CPP C++ Programming Lecture 16

CSE 333 Lecture 9 - intro to C++

III. Classes (Chap. 3)

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Lab 6. Out: Wednesday 9 March 2005

COMP322 - Introduction to C++

Introduction to Programming using C++

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

G52CPP C++ Programming Lecture 13

Function Templates. Consider the following function:

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

Computational Physics

The University of Nottingham

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Introduction to C++ Introduction to C++ 1

CPSC 427a: Object-Oriented Programming

Standard Library. Lecture 27. Containers. STL Containers. Standard Library

The Standard Template Library. An introduction

Object Oriented Design

Chapter 5. The Standard Template Library.

CSE 303: Concepts and Tools for Software Development

COMP322 - Introduction to C++ Lecture 01 - Introduction

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

EL2310 Scientific Programming

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

Outline. Variables Automatic type inference. Generic programming. Generic programming. Templates Template compilation

Due Date: See Blackboard

CS11 Intro C++ Spring 2018 Lecture 1

List, Stack, and Queues

Absolute C++ Walter Savitch

Computer Science II Lecture 2 Strings, Vectors and Recursion

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

COMP322 - Introduction to C++

Where do we go from here?

Lab # 02. Basic Elements of C++ _ Part1

Arrays. Week 4. Assylbek Jumagaliyev

Patterns: Working with Arrays

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

COMP 2355 Introduction to Systems Programming

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Course "Data Processing" Name: Master-1: Nuclear Energy Session /2018 Examen - Part A Page 1

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

CS

Due Date: See Blackboard

PHY4321 Summary Notes

Templates and Vectors

EL2310 Scientific Programming

Understanding main() function Input/Output Streams

Review Questions for Final Exam

Time(int h, int m, int s) { hrs = h; mins = m; secs = s; } void set(int h, int m, int s) { hrs = h; mins = m; secs = s; }

CS11 Introduction to C++ Fall Lecture 1

Streams. Rupesh Nasre.

CMSC 202 Midterm Exam 1 Fall 2015

Object Oriented Design

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

UEE1302 (1102) F10: Introduction to Computers and Programming

Lecture 14: more class, C++ streams

Transcription:

G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1

Welcome Back 2

Last lecture Operator Overloading Strings and streams 3

Operator overloading - what to know Know that you can change the meaning of operators Know that operator overloading is available as both a member function version and a global (non-member) function version Be able to provide the code for the overloading of an operator Parameter types, const? Return type Simple implementations 4

Questions to ask yourself Define as a member or as a global? If global then does it need to be a friend? What should the parameter types be? References? Make them const if you can What should the return type be? Should it return *this? Does it need to return a copy of the object? e.g. post-increment must return a copy Should the function be const? 5

My string comparison operator bool operator==( const std::string& s1, const std::string& s2) return 0 == strcmp( s1.c_str(), s2.c_str() ); Get the string as a char array int main () string str1( "Same" ); string str2( "Same" ); string str3( "Diff" ); printf( "str1 and str2 are %s\n", (str1 == str2)? "Same" : "Diff" ); printf( "str1 and str3 are %s\n", (str1 == str3)? "Same" : "Diff" ); printf( "str2 and str3 are %s\n", (str2 == str3)? "Same" : "Diff" ); 6

streams for input/output C++ input/output classes use streams Three standard stream objects exist already istream cin; (matches stdin) ostream cout; (matches stdout) ostream cerr; (matches stderr) Header file includes the declarations: #include <iostream> They are in std namespace Use std::cin, std::cout, etc >> and << operators are overloaded for input and output endl sent to a stream will output \n and flush 7

Example of output #include <iostream> using namespace std; Look in std namespace for the names which follow int main() e.g. cin, cout, cerr const char* str = "Test string"; int i = 1; Overloaded operator - input cin >> i; cout << str << " " << i << endl; cerr << str << endl; Header file for input AND output Overloaded operator - output return 0; 8

This lecture Template functions Template Classes Standard Template Library Only and introduction/overview 9

The plan now No more labs, so use the 2pm lectures for questions Friday 26 th April, 10am, Lecture 19 When is a duck an instrument? (Multiple Inheritance) Friday 26 th April, 2pm Optional How to create programs fast Thursday 2 nd May, 4pm, Lecture 20 Wrapping up (slicing problem, smart pointers) Friday 3 rd May, 10am, Revision Lecture Revision and exam strategy Friday 3 rd May, 2pm - Optional Any questions / examples What do you want to revise? 10

Function Overloading We can use function overloading to have multiple versions of the same function Consider the following functions: int mymax( int a, int b ) return a > b? a : b; float mymax( float a, float b ) return a > b? a : b; char mymax( char a, char b ) return a > b? a : b; It would be nice to create just the one 11

Template version int mymax( int a, int b ) return a > b? a : b; float mymax( float a, float b ) return a > b? a : b; char mymax( char a, char b ) return a > b? a : b; template < typename T > T mymax( T a, T b ) return a > b? a : b; 12

Template functions Templates specify how to create functions of a certain format, if they are ever needed, e.g.: template < typename T > T mymax( T a, T b ) return a > b? a : b; Note: you can use keyword class or typename : i.e. template < class T > Type placeholders are used, and are replaced implicitly Could use it as any type, e.g.: int i1 = 4, i2 = 14; int i3 = mymax( i1, i2 ); 13

What templates do The compiler will actually generate the functions which are needed, according to the parameters i.e. at compile time, new functions are created If there are any problems, it will not compile e.g. if new template class needs a function or operator which is not supported by the type This is NOT something done at runtime 14

Example for mymax #include <iostream> using namespace std; template < typename T > T mymax( T a, T b ) return a > b? a : b; So that compiler knows what cout is when we use it later (and what endl is) int main() int i1 = 4, i2 = 14; int i3 = mymax( i1, i2 ); cout << "mymax(" << i1 << "," << 12 << ") = " << i3 << endl; 15

Compiler generates a function #include <iostream> using namespace std; template < typename T > T mymax( T a, T b ) return a > b? a : b; int mymax( int a, int b ) int main() return a > b? a : b; int i1 = 4, i2 = 14; int i3 = mymax( i1, i2 ); cout << "mymax(" << i1 << "," << 12 << ") = " << i3 << endl; 16

How to create template functions The easy way to create these template functions: First manually generate a function for specific types Next replace all copies of the types by an identifier Then add the keyword template at the beginning and put the type(s) in the <> with keyword typename (or class) For example, an addition with casting function: int addcast( int a, float b ) return a + static_cast<int>(b); Becomes: template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); And can be used as: int val = addcast( 12, 4.65 ); 17

Example of addcast<t1,t2> #include <iostream> // cout using namespace std; template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); Creates a version which changes the float to an int and adds them int main() int val = addcast( 12, 4.65 ); cout << 12 << "+" << 4.65 << "=" << val << endl; return 0; 18

Question: Will this compile? #include <iostream> using namespace std; template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); class MyFloat public: MyFloat( float f ) : f(f) float f; ; Code in main: MyFloat f1(1.1); float f2 = 2.2; MyFloat f3 = addcast(f1,f2); cout << f3.f << endl; 19

The compilation error template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); class MyFloat public: MyFloat( float f ) : f(f) MyFloat f1(1.1); float f2 = 2.2; MyFloat f3 = addcast(f1,f2); cout << f3.f << endl; template1.cpp: In function T1 addcast(t1, T2) float f; [with T1 = MyFloat, T2 = float] : ; template1.cpp:32:28: instantiated from here template1.cpp:7:31: error: no match for operator+ in a + MyFloat(b) 20

Add an operator+ template <typename T1, typename T2> T1 addcast( T1 a, T2 b ) return a + static_cast<t1>(b); class MyFloat public: MyFloat( float f ) : f(f) MyFloat f1(1.1); float f2 = 2.2; MyFloat f3 = addcast(f1,f2); cout << f3.f << endl; MyFloat float operator+( f; const MyFloat& f1, const MyFloat& f2) ; MyFloat f( f1.f + f2.f ); return f; 21

Template classes 22

Template class You can make template forms of entire classes as well as individual functions Again the typename placeholder name (e.g. T) is replaced throughout the class You need to use it in both the class declaration and the member function implementations To alter class definition: Add template <typename T> at the start, as for template functions Then replace the templated type throughout the code 23

Template class : linked list class MyLinkedList struct Entry struct Entry* pnext; int idata; ; Entry* _phead; public: MyLinkedList() : _phead(null) void InsertHead( int idata ); template < typename T > class MyLinkedList struct Entry struct Entry* pnext; T tdata; ; Entry* _phead; public: MyLinkedList() : _phead(null) void InsertHead( T tdata ); ; void List(); ; void List(); 24

How to alter member functions Add prior to each member function definition: template <typename T> Add the <T> to the end of the class name in the member function implementation/definition: Example member function implementation: template <typename T> void MyLinkedList<T>::Store(T tdata) Find each occurrence of the templated type and replace it by the templated type name e.g. replace int with T in the example Note: typename can be replaced by class 25

The member functions void MyLinkedList:: InsertHead(int idata) Entry* pnewentry = new Entry(); pnewentry->idata = idata; pnewentry->pnext = _phead; _phead = pnewentry; void MyLinkedList::List() Entry* pentry = _phead; while( pentry!= NULL ) cout << pentry->idata << endl; pentry = pentry->pnext; template <typename T> void MyLinkedList<T>:: InsertHead(T tdata) Entry* pnewentry = new Entry(); pnewentry->tdata = tdata; pnewentry->pnext = _phead; _phead = pnewentry; template <typename T> void MyLinkedList<T>::List() Entry* pentry = _phead; while( pentry!= NULL ) cout << pentry->tdata << endl; pentry = pentry->pnext; 26

Using the template class int test1() MyLinkedList<float> olist; olist.inserthead( 1.1 ); olist.inserthead( 2.2 ); olist.inserthead( 3.3 ); olist.inserthead( 4.4 ); olist.inserthead( 5.5 ); olist.inserthead( 6.6 ); olist.list(); int test2() MyLinkedList<string> olist; olist.inserthead( "Adam" ); olist.inserthead( "Brian" ); olist.inserthead( "Carl" ); olist.inserthead( "Dave" ); olist.inserthead( "Eric" ); olist.inserthead( "Fred" ); // Following line would not compile: //olist.inserthead( 1.2 ); olist.list(); The class name is qualified with a type in angled brackets. Once specified, the type is fixed. Instantiations of the class are generated by the compiler as needed. 27

Exam: do I need to know all of this? Template functions Be able to recognise them Know what they do Be able to convert from a normal function to a template version Know the difference between a template function and a macro (#define) And the dangers of using #define Template classes Recognise them Be able to understand code which uses them Understand code using STL classes 28

STL container classes vector string map list set stack queue deque multimap multiset In std namespace Know that Standard Template Library exists If you go for C++ job interview, learn basics These are template classes e.g. vector<int> for vector of ints Also have iterators Track position/index in a container e.g. to iterate through a container And algorithms (over 70 of them) Apply to containers e.g. min(), max(), sort(), search() 29

Example of using vector #include <iostream> #include <string> #include <vector> using namespace std; int main() vector<char> v(10); // 10 elements int size = v.size(); cout << "Size " << size << endl; // Set each value for( int i=0 ; i < size ; i++ ) v[i] = i; // Iterate through vector vector<char>::iterator p = v.begin(); for( ; p!= v.end() ; p++ ) *p += 97; // Output the contents for( int i=0 ; i < size ; i++ ) cout << v[i] << endl; return 0; 30

Arrays of pointers #include <iostream> using namespace std; class Base public: Base() : i(1) virtual void out() cout <<"Base" <<i <<endl; int i; ; class Sub : public Base public: Sub() i = 2; void out() cout <<"Sub" <<i <<endl; ; Lec18a.cpp int main() Sub* arrayp1[3] = new Sub, new Sub, new Sub ; Base* arrayp2[3] = new Base, new Base, new Base ; // Output Array 1 for ( int i = 0 ; i < 3 ; i++ ) arrayp1[i]->out(); // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) arrayp2[i]->out(); // Copy Array 1 elements to 2 for ( int i = 0 ; i < 3 ; i++ ) arrayp2[i] = arrayp1[i]; // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) arrayp2[i]->out(); 31

Objects are not pointers #include <iostream> using namespace std; class Base public: Base() : i(1) virtual void out() cout <<"Base" <<i <<endl; int i; ; class Sub : public Base public: Sub() i = 2; void out() cout <<"Sub" <<i <<endl; ; Lec18b.cpp int main() Sub array1[3]; Base array2[3]; // Output Array 1 for ( int i = 0 ; i < 3 ; i++ ) array1[i].out(); // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) array2[i].out(); // Copy array 1 to 2 for ( int i = 0 ; i < 3 ; i++ ) array2[i] = array1[i]; // Output Array 2 for ( int i = 0 ; i < 3 ; i++ ) array2[i].out(); 32

Next lecture and beyond No more labs, so use the 2pm lectures for questions Friday 26 th April, 10am, Lecture 19 When is a duck an instrument? (Multiple Inheritance) Friday 26 th April, 2pm Optional How to create programs fast Thursday 2 nd May, 4pm, Lecture 20 Wrapping up (slicing problem, smart pointers) Friday 3 rd May, 10am, Revision Lecture Revision and exam strategy Friday 3 rd May, 2pm - Optional Any questions / examples What do you want to revise? 33