Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14.

Similar documents
CS24 Week 3 Lecture 1


Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

C C C C++ 2 ( ) C C++ 4 C C

Lecture on pointers, references, and arrays and vectors

Written by John Bell for CS 342, Spring 2018

Templates and Vectors

CS197c: Programming in C++

Bruce Merry. IOI Training Dec 2013

Fast Introduction to Object Oriented Programming and C++

G52CPP C++ Programming Lecture 16

GEA 2017, Week 4. February 21, 2017

G52CPP C++ Programming Lecture 20

Lab Instructor : Jean Lai

Partha Sarathi Mandal

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

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

CS 162, Lecture 25: Exam II Review. 30 May 2018

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

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 303: Concepts and Tools for Software Development

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

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

Recap: Pointers. int* int& *p &i &*&* ** * * * * IFMP 18, M. Schwerhoff

Object oriented programming

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Programming in C++: Assignment Week 8

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Unit 7. 'while' Loops

Chapter Four: Loops II

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

G52CPP C++ Programming Lecture 15

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

CS3157: Advanced Programming. Outline

explicit class and default definitions revision of SC22/WG21/N1582 =

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

COMP 2355 Introduction to Systems Programming

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

VIRTUAL FUNCTIONS Chapter 10

Extending Classes (contd.) (Chapter 15) Questions:

CSI33 Data Structures

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

Introduction to Programming using C++

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

CS302 Midterm Exam Answers & Grading James S. Plank September 30, 2010

The University of Nottingham

CS 11 C++ track: lecture 1

CS93SI Handout 04 Spring 2006 Apr Review Answers

CS 247: Software Engineering Principles. ADT Design

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

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

CSE 333 Lecture 9 - intro to C++

Polymorphism Part 1 1

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

Benefits of Data Encapsulation. Internal and External Views. Lecture 4 : Data Abstraction. Data Encapsulation. Information Hiding

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

G52CPP C++ Programming Lecture 13

CSC1322 Object-Oriented Programming Concepts

Polymorphism. Zimmer CSCI 330

W3101: Programming Languages C++ Ramana Isukapalli

Cpt S 122 Data Structures. Introduction to C++ Part II

Linked List using a Sentinel

CE221 Programming in C++ Part 1 Introduction

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

Shahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

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

University of Michigan EECS 183: Elem. Programming Concepts Fall 2011 Exam 1: Part 1: Form 1. Professors: ML Dorf, Elliot Soloway

Comp151. Generic Programming: Container Classes

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Object-Oriented Programming

ECE 461 Fall 2011, Final Exam

Programming, numerics and optimization

A brief introduction to C++

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

CS 211 Winter 2004 Sample Final Exam (Solutions)

Lectures 19, 20, 21. two valid iterators in [first, last) such that i precedes j, then *j is not less than *i.

Engineering Tools III: OOP in C++

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

PIC 10A. Lecture 17: Classes III, overloading

Introduction Of Classes ( OOPS )

CS201 - Introduction to Programming Glossary By

GCC : From 2.95 to 3.2

C++ For Science and Engineering Lecture 12

Data Structures Lecture 3 Order Notation and Recursion

Implementing vector<>

Module 7 b. -Namespaces -Exceptions handling

for (int i = 1; i <= 3; i++) { do { cout << "Enter a positive integer: "; cin >> n;

III. Classes (Chap. 3)

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

CPSC 427: Object-Oriented Programming

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CSE030 Fall 2012 Final Exam Friday, December 14, PM

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

G52CPP C++ Programming Lecture 18

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

Review Questions II KEY

Transcription:

Lecture 14 1

Exceptions Iterators Random numbers Casting Enumerations Pairs The Big Three Outline 2

Error Handling It is often easier to write a program by first assuming that nothing incorrect will happen Once it works correctly for the expected cases, add code to handle the exceptional cases Exception handling is commonly used to handle error situations Once an error is handled, it is no longer an error 3

Motivational XKCD 4

Exceptions In C++, exception handling proceeds by: Some library software or your code signals that something unusual has happened This is called throwing an exception At some other place in your program you place the code that deals with the exceptional case This is called handling or catching the exception 5

#include <iostream> using namespace std; int main() double a, b; Example cin >> a >> b; cout << ( a / b ) << endl; return 0;./a 3 5 0.6./a 3 0 inf 6

Try-Throw-Catch #include <iostream> using namespace std; int main() double a, b; cin >> a >> b; try if ( b == 0 ) throw a; cout << ( a / b ) << endl; catch (double a) cout << "Can't divide " << a << " by zero" << endl; return 0;./a 3 5 0.6./a 3 0 Can't divide 3 by zero 7

The Basics In C++ you can throw any type Commonly a class that carries useful information to catch Code within the try block is suspected to throw an exception Similar to if-else, but with messaging There can be multiple catch blocks with different types 8

Advanced Example #include <iostream> using namespace std; class DivideException public: DivideException(double val): val( val ) double getval() return val; private: double val; ; double div(double a, double b) throw (DivideException) if ( b == 0 ) throw DivideException( a ); int main() double a, b; cin >> a >> b; try cout << div( a, b ) << endl; catch (DivideException e) cout << "Can't divide " << e.getval() << " by zero" << endl; return 0; return ( a / b ); 9

Iterators An iterator is a generalization of a pointer Typically implemented using a pointer, but saves you from the details and provides a uniform interface to numerous collection classes Think of an iterator like a pointer Has many similar operators overloaded 10

Motivational XKCD 11

Common Usage #include <iostream> #include <vector> using namespace std; int main() vector<int> v; v.push_back( 1 ); v.push_back( 2 ); v.push_back( 3 ); for ( vector<int>::iterator it=v.begin(); it!=v.end(); it++ ) cout << *it << endl; return 0; 1 2 3 12

Random Number Generator With most computers it is difficult to devise a method by which to produce truly random numbers These are useful in many situations (e.g. games, statistic simulation, AI, ) A random number generator (RNG) is an algorithm designed to generate a sequence of numbers or symbols that appear random 13

Motivational XKCD 14

The Basic Pattern With most RNGs, there is the concept of a seed a value that is used to produce a distinct sequence If you provide the same seed, you should always get the same sequence So Seed the RNG Ask for as many random values as you need May need computation to get in useful bounds 15

#include <iostream> #include <cstdlib> using namespace std; Example int main() srand( 42 ); // seed the rng for ( int i=0; i<5; i++ ) // rand() = [0, RAND_MAX] cout << ( rand() % 100 ) << endl; return 0; 94 23 9 43 26 16

Casting Whenever you need to convert between data types, a form of type casting is involved There are many issues, including pointers, inheritance, const 17

Motivational XKCD (a stretch) 18

Example #include <iostream> #include <cstdlib> using namespace std; class Base public: void foo() cout << "Base" << endl; ; class Derived: public Base public: void foo() cout << "Derived" << endl; ; int main() Base* b = new Base(); Base* d = new Derived(); b- >foo(); d- >foo(); ((Derived*) d)- >foo(); return 0; Base Base Derived 19

Enumerations A distinct type whose value is restricted to one of several explicitly named constants The values of the constants are values of an integral type Useful to let the compiler keep you from making mistakes when you know the range of values 20

Motivational XKCD 21

#include <iostream> using namespace std; Example enum suit hearts, diamonds, spades, clubs ; int main() suit a = hearts; suit b = spades; cout << ( a == b ) << endl; return 0; 0 22

Pairs It s often useful to bundle two variables together, and so there is a C++ pair class Pairs are templated, and generically referred to by the first or second element 23

Motivational XKCD 24

#include <iostream> #include <utility> using namespace std; Example int main() pair<char, int> a = make_pair<char, int>( 'a', 1 ); cout << a.first << a.second << endl; return 0; a1 25

Deep vs. Shallow Copies When assigning objects, a shallow copy is performed Values are copied between instances This becomes problematic when dealing with dynamically allocated memory All that is copied is a memory address, and so now two objects point to the same memory Rule of the Big Three. If you have any dynamically allocated storage in a class, you must provide: 1. A destructor 2. A copy constructor 3. An overloaded assignment operator 26

Motivational XKCD 27

Shallow Example #include <iostream> using namespace std; class Foo public: int bar; ; int main() Foo a, b; a.bar = 5; b = a; a.bar = 7; cout << a.bar << " " << b.bar << endl; 7 5 return 0; 28

Pointer Problem #include <iostream> using namespace std; class Foo public: int* bar; ; int main() Foo a, b; a.bar = new int(5); b = a; *(a.bar) = 7; cout << *(a.bar) << " " << *(b.bar) << endl; return 0; 7 7 29

The Big Three class Foo public: Foo() bar = new int(0); Foo(int x) bar = new int(x); int main() Foo a(5), b; Foo c(a); b = a; ; Foo(const Foo& other) bar = new int( *(other.bar) ); ~Foo() delete bar; Foo& operator =(const Foo& other) *bar = *(other.bar); return *this; int* bar; *(a.bar) = 7; cout << *(a.bar) << " " << *(b.bar) << " " << *(c.bar) << endl; return 0; 7 5 5 30

Wrap Up There are many aspects of C++ that we did not cover in depth I hope you continue to explore programming in C++ and other languages Much of what we covered here has its parallels in other languages 31

End-of-Semester XKCD 32