Module 4. l Graph Algorithms-MST. l HW3. l OO class point. C++ for C Programmers by Ira Pohl

Size: px
Start display at page:

Download "Module 4. l Graph Algorithms-MST. l HW3. l OO class point. C++ for C Programmers by Ira Pohl"

Transcription

1 Module 4 Graph Algorithms-MST HW3 OO class point

2 Homework Week 3 Already built a graph (Abstract Data Type) Used Dijkstra algorithm to generate graph based on density and size Computed average length

3 Minimum Spanning Tree Assume a graph is connected with arbitrary edge costs Cij. Find a spanning tree of least cost. A spanning tree is a set of edges within the graph that connects all the nodes and where there is no cycle.

4 Extra Credit : Color idea Assume each edge has one of three colors Red, Blue, Green Find MST when edges must be of a specified color or pair of colors.

5 Quiz: Enum color enum color{ RED, BLUE, GREEN}; Why were the colors capitalized? What int value is GREEN? How can we overload << to print RED

6 Answers Convention to use all caps for enumeration constants GREEN is 2 out& operator<<(ostream& out, color c) { ---what goes here return??? }

7 C++11 enum classes Strongly typed enums - enum classes enum class Color{RED, GREEN, BLUE}; enum class Traffic{RED, YELLOW, GREEN}; class indicates that each enum type is different. and not comparable to other enum types. Color::RED!= Traffic::RED

8 Jarnik-Prim MST ### This algorithm was developed in 1930 by the Czech mathematician Vojtěch Jarník and rediscovered by Robert Prim in Prim s algorithm starts with a single vertex and repeatedly joins the minimum-weight edge that joins the tree to a non-tree vertex. At each step the tree is a minimum spanning tree of the vertices that have been processed thus far.

9 Minimum Spanning Tree

10 Minimum Spanning Tree Start at A Nearest is E Pick nearest next node until All nodes in graph or no more nodes to connect

11 Quiz If all edges have unit cost and a graph has 10 nodes and it has an MST what will be its cost? Same question for n nodes?

12 Answer 10 nodes : MST 9 edges : therefore 9 N nodes: therefore N-1

13 Minimum Spanning Tree 2

14 Prim pseudocode Given a graph, G, with edges E of the form (v1, v2) and vertices V dist : array of distances from the source to each vertex edges: array indicating, for a given vertex, which vertex in the tree it is closest to i : loop index MST : list of finished vertices U : list or heap unfinished vertices /* Initialization: set every distance to INFINITY until we discover a way to link a vertex to the spanning tree */ for i = 0 to V - 1 dist[i] = INFINITY edge[i] = NULL C++ for C Programmers end by Ira Pohl

15 Prim pseudocode pick a vertex, s, - say vertex 0 dist[s] = 0 while(mst is missing a vertex) pick the vertex, v, in U with the shortest edge to the group of vertices in the spanning tree add v to MST for each edge of v, (v1, v2) if(length(v1, v2) < dist[v2]) dist[v2] = length(v1, v2) edges[v2] = v1 possibly update U, depending on implementation end if end for end while

16 Prim is greedy Prim (and Dijkstra) are called greedy algorithms they take a locally best next element and this leads to a globally best solution greedy algorithm when optimal tend to be very efficient when non-optimal they still might be heuristically okay

17 Kruskal Pseudocode ### Create a forest F (a set of trees), where each vertex in the graph is a separate tree. Create a set S containing all the edges in the graph. While S is nonempty and F is not yet spanning remove an edge with minimum weight from S if that edge connects two different trees, then add it to the forest, combining two trees into a single tree otherwise discard that edge. At the termination of the algorithm, the forest has only one component and forms a minimum spanning tree of the graph.

18 Kruskal simulate

19 Quiz How would you change algorithm to find a maximum spanning tree ie greatest cost spanning tree.

20 Answer Same structure but pick largest cost edges.

21 Further C++ ideas Ch6 ### Operator overloading Friend functions

22 OOP Principle User defined types should be indistinguishable from native types Operator overloading and conversion allows us to implement this principle

23 Point and conversions class point{ public: point (double u):x(u), y(0.0){}. private double x, y; };

24 Convert double to point point s; double d = 3.5; s = d; //implicit conversion s = static_cast<point>(d); //explicit

25 Convert point to double Can t get at definition of native type but C++ can do as follows: point ::operator double() { return sqrt(x*x +y*y);} d = s; //this would now work??? Not always a good idea maybe opaque

26 C++11 explicit suppress conversion explicit keyword in front of a constructor of one argument turns off its ability to be used implicitly for conevrsion explicit point::point(double d) {.. // code };

27 Overloading and function selection Exact match to signature Try standard promotions - eg int to double Try standard type conversions eg int to short Try user defined conversions Use a match to ellipsis if found ( ) Read pp on rational

28 Friend functions and classes Googly with Nappie having access to their Private parts

29 Friend function class point{ }; private x,y; //restricted to class methods ostream& <<operator(ostream& out, point p) { out << ( << x <<, <<y << ) ; return out;} FAILS because x and y are private

30 Friend is important for << class point{ friend ostream& operator<<(ostream& ); }; private x,y; //restricted to class methods By having this be a class friend we allow it access priveleges and unlike a class method it does not have a dot argument

31 Operator+ class point{ public: point operator+(point p) { return point(x+p.x, y+p.y);}. private double x, y; };

32 Typical friend operator + (type arg1, type arg2) Versus classname : : operator + (type arg 1) // here this provides arg1

33 Point binary + point a, b(2, 1), c(0.5, 6);.. a = b + c; // b.operator+(c) Now if we used a friend function which is preferred we would get a = b + c; // operator+(b, c) Now both arguments subject to symmetrical semantics as in function arg conversions

34 Operator overloading Need to be very careful Need to conform to rules from the math domain - eg point, polynomial, rational but not window Need to be comprehensive + defined, so would expect -, *, /

35 Quiz: Not all operators in C++ can be overloaded; One of these is scope resolution; Another is the only ternary operator in C++; What is it and why is not overloadable?

36 Answer:?: is ternary It would be ugly to overload it and would not have a natural semantics. Bye?:

37 Standard Template Library ### STL STL C++11 -new

38 Three Legged St oo l STL Containers Algorithms Iterators

39 Standard Template Library Three Legged Stool: Containers: vector, list, map Iterators: forward, backward, random access Algorithms: sort, permute

40 Quiz Name two standard sorting algorithms What is their expected time? Worst case time?

41 Answer Bubblesort, Quicksort Bubblesort n*n Quicksort n*ln(n) - worst case n*n

42 Example ### // Simple STL vector program #include <iostream> #include <vector> using namespace std; int main () { vector<int> v(100); //allocate space **vector is a template and is a random access container replace array in C++

43 Example code for (int i = 0; i < 100; ++i) v[i] = i;//index thru like an array for (vector<int>::iterator p = v.begin(); p!= v.end(); ++p) cout << *p << '\t'; cout << endl; } **second for used iterators note the declaration, and it is safer no off by 1 errors.

44 begin() end() methods Here we use a vector and its associated iterator. Think of p as conceptually a pointer. It has two endpoints that define its range: (v.begin(), v.end()) where v.begin() stores a value, but v.end() does not.

45 C feature use auto ### for (vector<int>::iterator p = v.begin(); cout << *p << '\t'; cout << endl; ) for (auto p = v.begin(); ) auto is used to declare types that can be deduced from context and is no longer a storage specifier.

46 More auto examples auto i = 3; //typical would be int auto d = 3.7; //would be double auto c = d; //would be double

47 Quiz deduce type auto c = B ;

48 Answer: auto c = B ; c is a char type

49 Vector methods v.size() get current size v.resize(int size) resize the vector Constructors vector<t> v; empty sequence vector<t> v(n); size n with default constructor T() called for each element vector<t> v(n, value) ; value is of type T Or convertible to T and is value of each element

50 Vector + file IO // Simple STL vector program with file IO #include <fstream> //file io #include <iostream> #include <vector> using namespace std;

51 Read from a file int main () { vector<int> v(10); ifstream ifp("data", ios::in); int i = 0; while(!ifp.eof() ) { ifp >> v[i++]; if (i%9 ==0) v.resize(v.size() +10); }

52 Simple file input ifstream ifp("data", ios::in); Input file pointer opened for reading data not a full path name so it must exist and be in the local directory

53 More code v.resize(i-1); //get rid of extra elements for (vector<int>::iterator p = v.begin(); p!= v.end(); ++p) cout << *p << '\t'; cout << endl; }

54 Iterator idiom for (vector<int>::iterator p = v.begin();p!= v.end(); ++p) *** declare iterator and intialize to begin *** ++p auto increment iterator(pointer) to advance cout << *p << '\t'; *** dereference iterator to get T value of object being pointed at

55 Quiz: Avoiding bounds errors for(int i =0; i<=upper_bound; ++i) sum = sum + data[i]; What goes wrong?

56 Answer: <= upper_bound is usually not right Off-by one

57 C++11 New for statement ### for (declaration : expression) Statement This is the range for statement A simple example that takes care of the bounds error problem in arrays for(double d : data) sum +=d; So data is an array of doubles such as double data[upper_bound]

58 Range for The expression can be an array, a sequence container, a string. They are conceptually expected to have begin and end members. Another example: For(auto &element : data) //auto infers type element = element + 2; //allows mutate

59 STL input file example ### //read a series of words into a vector #include<iostream> #include<fstream> #include<algorithm> #include<vector> using namespace std; void getw(string& t, ifstream& in){ in>> t; }

60 Read in words int read_string(vector<string> &words, ifstream& in) { int i = 0; while(!in.eof())//sentinel getw(words[i++], in); return (i - 1); }

61 main int main() { ifstream in("text"); vector<string> w(1000); //hope 1000 is enough int howmany = read_string(w, in); w.resize(howmany); sort(w.begin(), w.end()); for( auto str : w) cout << str << "\t" ; }

62 Sort algorithm sort(w.begin(), w.end()); The sort() routine is found in the STL algorithm library. It is an efficient form of quicksort [Hoare]. If you don t think so try to write your own and compare by timing it on a large number of elements. sort() uses two iterator positions to sort the elements in the vector w. This sort routine expects that the elements pointed at can be randomly accessed.

63 Iterators categories ###

64 Iterator categories In STL there are five iterator categories: input (weakest), -read, single pass output, - write, single pass forward, read and write multipass -1D bidirectional, multi-pass + 2 directions Random access (strongest), anywhere

65 Algorithms and Iterators In STL the design principle is to use the weakest iterator that accomodates the most efficient algorithm. Quicksort requires random access. As a consequence it cannot be used on a nonrandom access container such as a list.

66 Input Iterator The iterator hierarchy: 1.input iterator: The input iterator must allow the elements to be searched in a forward direction one-by-one. This requires that operator ++ be defined ("advance the iterator") and dereferencing operator *.

67 Input it Canonically accessing elements sequentially in an input stream requires this minimal set of operations. Similarly using a find(elem) in a collection searched sequentially has these requirements. Also input iterators have == and!= defined.

68 Example input it //use an input iterator #include<iostream> #include<fstream> #include<numeric> using namespace std;

69 Example int main() { ifstream myin("data"); istream_iterator<int> in(myin); istream_iterator<int> eos; cout << "Sum of data is " << accumulate(in, eos, 0) << endl; }

70 accumulate() The algorithm accumulate() is from the <numeric> library accumulate(input_it, input_it, value) value is usually 0 accumulate over the specified range

71 Quiz: int data[4] = {1,2,3,4}; cout << accumulate(data, data + 4, 5); What gets printed

72 Answer:

73 Output a random graph ### #include <iostream> #include <ctime> #include <cstdlib> #include <fstream> using namespace std; { } double prob() return (static_cast<double>(rand())/rand_max);

74 Will represent graph with matrix { int main(void) int size = 15; double density ; cout << "graph size?" << endl; cin >> size; cout << "graph density (0, 1)?" << endl; cin >> density; bool** graph; int** color; int** cost; srand(time(0)); //seed random number generator

75 Create matrices off heap } graph = new bool*[size]; color = new int*[size]; cost = new int*[size]; for(int i = 0; i <size; ++i){ graph[i] = new bool[size]; color[i] = new int[size]; cost[i] = new int[size];

76 Generate graph for (int i = 0; i < size; ++i) //generate undirected edges for(int j = i; j < size; ++j) if (i == j) graph[i][j]= false; //no loops else graph[i][j] = graph[j][i] = (prob() < density); for (int i = 0; i < size; ++i) //generate costs and color for(int j = i; j < size; ++j) if (graph[i][j]){ color[i][j] = color[j][i] = rand()% 3; cost[i][j] = cost[j][i] = prob()* 30; }

77 Create output file ofstream outp("graph_data.txt"); outp << size << "\n"; for (int i = 0; i < size; ++i) for(int j = 0; j < size; ++j){ if ( graph[i][j]) outp << i <<'\t' << j << '\t' << cost[i][j] << '\t' << color[i][j] << '\t'; }

78 Next Section Second Half of the Class More advanced C++ with new C++11 features Build a Game

C++ and OO. l C++ classes and OO. l More Examples. l HW2. C++ for C Programmers by Ira Pohl

C++ and OO. l C++ classes and OO. l More Examples. l HW2. C++ for C Programmers by Ira Pohl C++ and OO C++ classes and OO More Examples HW2 Objects C++ and OO What happens with a declaration int i, j = 3; Declares; allocates ; initializes For a simple native type this happens automatically via

More information

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

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming What the heck is STL???? Another hard to understand and lazy to implement stuff? Standard Template Library The standard template

More information

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points.

COP 3014: Fall Final Study Guide. December 5, You will have an opportunity to earn 15 extra credit points. COP 3014: Fall 2017 Final Study Guide December 5, 2017 The test consists of 1. 15 multiple choice questions - 30 points 2. 2 find the output questions - 20 points 3. 2 code writing questions - 30 points

More information

CSE 100 Minimum Spanning Trees Prim s and Kruskal

CSE 100 Minimum Spanning Trees Prim s and Kruskal CSE 100 Minimum Spanning Trees Prim s and Kruskal Your Turn The array of vertices, which include dist, prev, and done fields (initialize dist to INFINITY and done to false ): V0: dist= prev= done= adj:

More information

Spanning Trees. Lecture 20 CS2110 Spring 2015

Spanning Trees. Lecture 20 CS2110 Spring 2015 1 Spanning Trees Lecture 0 CS110 Spring 01 1 Undirected trees An undirected graph is a tree if there is exactly one simple path between any pair of vertices Root of tree? It doesn t matter choose any vertex

More information

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

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

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

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed

More information

C Standard. l C++ For C Programmers :2 nd half. l C++11 feature of the day. l STL. C++ for C Programmers by Ira Pohl

C Standard. l C++ For C Programmers :2 nd half. l C++11 feature of the day. l STL. C++ for C Programmers by Ira Pohl C++ 2011 Standard C++ For C Programmers :2 nd half C++11 feature of the day STL Part I You have completed Part I, and: Know basic C++ Have coded both Min Spanning Tree and Dijkstra s algorithm Followed

More information

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

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

CSE030 Fall 2012 Final Exam Friday, December 14, PM

CSE030 Fall 2012 Final Exam Friday, December 14, PM CSE030 Fall 2012 Final Exam Friday, December 14, 2012 3-6PM Write your name here and at the top of each page! Name: Select your lab session: Tuesdays Thursdays Paper. If you have any questions or need

More information

CS2141 Software Development using C/C++ C++ Basics

CS2141 Software Development using C/C++ C++ Basics CS2141 Software Development using C/C++ C++ Basics Integers Basic Types Can be short, long, or just plain int C++ does not define the size of them other than short

More information

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

File Operations. Lecture 16 COP 3014 Spring April 18, 2018 File Operations Lecture 16 COP 3014 Spring 2018 April 18, 2018 Input/Ouput to and from files File input and file output is an essential in programming. Most software involves more than keyboard input and

More information

PIC 10A. Final Review

PIC 10A. Final Review PIC 10A Final Review Final exam Thursday, December 18, 2014 8:00 AM - 11:00 AM MS 5200. In our usual class room. (Verify on my.ucla.edu!!) The final exam is worth 30% of your grade, same weight as 2 midterms.

More information

Review Questions for Final Exam

Review Questions for Final Exam CS 102 / ECE 206 Spring 11 Review Questions for Final Exam The following review questions are similar to the kinds of questions you will be expected to answer on the Final Exam, which will cover LCR, chs.

More information

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1

Lecture 12. Monday, February 7 CS 215 Fundamentals of Programming II - Lecture 12 1 Lecture 12 Log into Linux. Copy files on csserver in /home/hwang/cs215/lecture12/*.* Reminder: Practical Exam 1 is Wednesday 3pm-5pm in KC-267. Questions about Project 2 or Homework 6? Submission system

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

10/31/18. About A6, Prelim 2. Spanning Trees, greedy algorithms. Facts about trees. Undirected trees

10/31/18. About A6, Prelim 2. Spanning Trees, greedy algorithms. Facts about trees. Undirected trees //8 About A, Prelim Spanning Trees, greedy algorithms Lecture CS Fall 8 Prelim : Thursday, November. Visit exams page of course website and read carefully to find out when you take it (: or 7:) and what

More information

Spanning Trees, greedy algorithms. Lecture 20 CS2110 Fall 2018

Spanning Trees, greedy algorithms. Lecture 20 CS2110 Fall 2018 1 Spanning Trees, greedy algorithms Lecture 20 CS2110 Fall 2018 1 About A6, Prelim 2 Prelim 2: Thursday, 15 November. Visit exams page of course website and read carefully to find out when you take it

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

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

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test

More information

Module Operator Overloading and Type Conversion. Table of Contents

Module Operator Overloading and Type Conversion. Table of Contents 1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading

More information

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

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can

More information

C++ For C Programmers Week 1 Part 1

C++ For C Programmers Week 1 Part 1 C++ For C Programmers Week 1 Part 1 Overview and Course Organization C++ as a Better C Problem 1 Convert C Code to be posted Course work 1. Homework 3 Programs to Code 2. One Final- closed book C++ is

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Review: C++ Basic Concepts. Dr. Yingwu Zhu Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

Scientific Computing

Scientific Computing Scientific Computing Martin Lotz School of Mathematics The University of Manchester Lecture 1, September 22, 2014 Outline Course Overview Programming Basics The C++ Programming Language Outline Course

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

CS 247: Software Engineering Principles. ADT Design

CS 247: Software Engineering Principles. ADT Design CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data

More information

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,

More information

pointers & references

pointers & references pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using

More information

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

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. C++ Kitchen Sink. Lecture 14. 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

More information

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

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47 Lecture 8 Xiaoguang Wang STAT 598W February 13th, 2014 (STAT 598W) Lecture 8 1 / 47 Outline 1 Introduction: C++ 2 Containers 3 Classes (STAT 598W) Lecture 8 2 / 47 Outline 1 Introduction: C++ 2 Containers

More information

PIC10B/1 Winter 2014 Exam I Study Guide

PIC10B/1 Winter 2014 Exam I Study Guide PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand

More information

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis C++ Programming Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis michail.lampis@dauphine.fr Classes These (and the previous) slides demonstrate a number of C++ features related

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information

Spanning Trees, greedy algorithms. Lecture 22 CS2110 Fall 2017

Spanning Trees, greedy algorithms. Lecture 22 CS2110 Fall 2017 1 Spanning Trees, greedy algorithms Lecture 22 CS2110 Fall 2017 1 We demo A8 Your space ship is on earth, and you hear a distress signal from a distance Planet X. Your job: 1. Rescue stage: Fly your ship

More information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

More information

CS197c: Programming in C++

CS197c: Programming in C++ CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website

More information

Templates and Vectors

Templates and Vectors Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

CS 211 Winter 2004 Sample Final Exam (Solutions)

CS 211 Winter 2004 Sample Final Exam (Solutions) CS 211 Winter 2004 Sample Final Exam (Solutions) Instructor: Brian Dennis, Assistant Professor TAs: Tom Lechner, Rachel Goldsborough, Bin Lin March 16, 2004 Your Name: There are 6 problems on this exam.

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

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

for (int i = 1; i <= 3; i++) { do { cout << Enter a positive integer: ; cin >> n; // Workshop 1 #include using namespace std; int main () int n, k; int sumdigits; for (int i = 1; i n; cin.clear (); cin.ignore (100,

More information

Spanning Trees 4/19/17. Prelim 2, assignments. Undirected trees

Spanning Trees 4/19/17. Prelim 2, assignments. Undirected trees /9/7 Prelim, assignments Prelim is Tuesday. See the course webpage for details. Scope: up to but not including today s lecture. See the review guide for details. Deadline for submitting conflicts has passed.

More information

Spanning Trees. Lecture 22 CS2110 Spring 2017

Spanning Trees. Lecture 22 CS2110 Spring 2017 1 Spanning Trees Lecture 22 CS2110 Spring 2017 1 Prelim 2, assignments Prelim 2 is Tuesday. See the course webpage for details. Scope: up to but not including today s lecture. See the review guide for

More information

Review Questions for Final Exam KEY

Review Questions for Final Exam KEY CS 102 / ECE 206 Spring 11 Review Questions for Final Exam KEY The following review questions are similar to the kinds of questions you will be expected to answer on the Final Exam, which will cover LCR,

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions. Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'

More information

Documentation. Programming / Documentation Slide 42

Documentation.   Programming / Documentation Slide 42 Documentation http://www.math.upb.de/~robsy/lehre/programmierkurs2008/ Programming / Documentation Slide 42 Memory Management (I) There are several types of memory which a program can access: Stack Every

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files. C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

Use the dot operator to access a member of a specific object.

Use the dot operator to access a member of a specific object. Lab 16 Class A class is a data type that can contain several parts, which are called members. There are two types of members, data member and functions. An object is an instance of a class, and each object

More information

Crash Course into. Prof. Dr. Renato Pajarola

Crash Course into. Prof. Dr. Renato Pajarola Crash Course into Prof. Dr. Renato Pajarola These slides may not be copied or distributed without explicit permission by all original copyright holders C Language Low-level programming language General

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Template based set of collection classes STL collection types (container types)

Template based set of collection classes STL collection types (container types) STL Collection Types Template based set of collection classes STL collection types (container types) Sequences vector - collection of elements of type T list - doubly linked list, only sequential access

More information

Chapter 5. The Standard Template Library.

Chapter 5. The Standard Template Library. Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,

More information

Object oriented programming

Object oriented programming Exercises 12 Version 1.0, 9 May, 2017 Table of Contents 1. Virtual destructor and example problems...................................... 1 1.1. Virtual destructor.......................................................

More information

Module 9. Templates & STL

Module 9. Templates & STL Module 9 Templates & STL Objectives In this module Learn about templates Construct function templates and class templates STL 2 Introduction Templates: enable you to write generic code for related functions

More information

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

Topics. bool and string types input/output library functions comments memory allocation templates classes C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

CSE 100: GRAPH ALGORITHMS

CSE 100: GRAPH ALGORITHMS CSE 100: GRAPH ALGORITHMS 2 Graphs: Example A directed graph V5 V = { V = E = { E Path: 3 Graphs: Definitions A directed graph V5 V6 A graph G = (V,E) consists of a set of vertices V and a set of edges

More information

CS11 Advanced C++ Spring 2018 Lecture 2

CS11 Advanced C++ Spring 2018 Lecture 2 CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are

More information

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine Homework 5 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 13, 2013 Question 1 Consider the following Java definition of a mutable string class. class MutableString private char[] chars

More information

Working with Batches of Data

Working with Batches of Data Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2012/csc1254.html 2 Abstract So far we looked at simple read a string print a string problems. Now we will look at more complex problems

More information

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8

More information

Exceptions, Templates, and the STL

Exceptions, Templates, and the STL Exceptions, Templates, and the STL CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 16 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/

More information

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

Lambda functions. Zoltán Porkoláb: C++11/14 1 Lambda functions Terminology How it is compiled Capture by value and reference Mutable lambdas Use of this Init capture and generalized lambdas in C++14 Constexpr lambda and capture *this and C++17 Zoltán

More information

STL: C++ Standard Library

STL: C++ Standard Library STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms

More information

Chapter 2. Procedural Programming

Chapter 2. Procedural Programming Chapter 2 Procedural Programming 2: Preview Basic concepts that are similar in both Java and C++, including: standard data types control structures I/O functions Dynamic memory management, and some basic

More information

Object Reference and Memory Allocation. Questions:

Object Reference and Memory Allocation. Questions: Object Reference and Memory Allocation Questions: 1 1. What is the difference between the following declarations? const T* p; T* const p = new T(..constructor args..); 2 2. Is the following C++ syntax

More information

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

G52CPP C++ Programming Lecture 18. Dr Jason Atkin G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that

More information

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points) Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Lecture 05 - I/O using the standard library, stl containers, stl algorithms Dan Pomerantz School of Computer Science 5 February 2013 Basic I/O in C++ Recall that in C, we

More information

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

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations Outline 12.1 Test-Driving the Craps Game Application 12.2 Random Number Generation 12.3 Using an enum in the Craps

More information

Review for Test 1 (Chapter 1-5)

Review for Test 1 (Chapter 1-5) Review for Test 1 (Chapter 1-5) 1. Software development 1. Pre-conditions and Post-conditions 2. Running time analysis Big O Timing loops and nested loops 1) Write the simplest big-o expression to describe

More information

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

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers. cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... today: language basics: identifiers, data types, operators, type conversions, branching and looping, program structure

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

G52CPP C++ Programming Lecture 18

G52CPP C++ Programming Lecture 18 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

More information

Operator overloading: extra examples

Operator overloading: extra examples Operator overloading: extra examples CS319: Scientific Computing (with C++) Niall Madden Week 8: some extra examples, to supplement what was covered in class 1 Eg 1: Points in the (x, y)-plane Overloading

More information

Introduction to C ++

Introduction to C ++ Introduction to C ++ Thomas Branch tcb06@ic.ac.uk Imperial College Software Society October 18, 2012 1 / 48 Buy Software Soc. s Free Membership at https://www.imperialcollegeunion.org/shop/ club-society-project-products/software-products/436/

More information

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

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. Welcome to Teach Yourself p. viii Acknowledgments p. xv Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p. 6 Standard C++: A Programming Language and a Library p. 8

More information

PIC 10A. Final Review: Part I

PIC 10A. Final Review: Part I PIC 10A Final Review: Part I Final exam The final exam is worth 30% of your grade, same weight as 2 midterms. Could be 50% if grading option 2 turns out better for you. Length is also roughly 2 midterms

More information

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this

Lecture Notes. char myarray [ ] = {0, 0, 0, 0, 0 } ; The memory diagram associated with the array can be drawn like this Lecture Notes Array Review An array in C++ is a contiguous block of memory. Since a char is 1 byte, then an array of 5 chars is 5 bytes. For example, if you execute the following C++ code you will allocate

More information

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary Reading from and Writing to Files Section 3.12 & 13.1 & 13.5 11/3/08 CS150 Introduction to Computer Science 1 1 Files (3.12) Data stored in variables is temporary We will learn how to write programs that

More information

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter

More information

use static size for this buffer

use static size for this buffer Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation

More information

Chapter 14 Sequential Access Files

Chapter 14 Sequential Access Files Chapter 14 Sequential Access Files Objectives Create file objects Open a sequential access file Determine whether a sequential access file was opened successfully Write data to a sequential access file

More information

G52CPP C++ Programming Lecture 17

G52CPP C++ Programming Lecture 17 G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions

More information

Object Oriented Programming using C++

Object Oriented Programming using C++ Object Oriented Programming using C++ Overview Problem Solving Features of an OOL Basic Syntax Programming Paradigms Solving a Programming Problem Analysis Design Coding Management Programming paradigms

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

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

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Fundamentals of Programming Session 25

Fundamentals of Programming Session 25 Fundamentals of Programming Session 25 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Section 1: True / False (2 points each, 30 pts total)

Section 1: True / False (2 points each, 30 pts total) Section 1: True / False (2 points each, 30 pts total) Circle the word TRUE or the word FALSE. If neither is circled, both are circled, or it impossible to tell which is circled, your answer will be considered

More information

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?

More information

A <Basic> C++ Course

A <Basic> C++ Course A C++ Course 5 Constructors / destructors operator overloading Julien Deantoni adapted from Jean-Paul Rigault courses This Week A little reminder Constructor / destructor Operator overloading Programmation

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information