Lecture Slides-CPlusPlus LectureNotes Module2
Lecture Slides-CPlusPlus LectureNotes Module2
!!
!!
Generic Programming
1. Relating to or descriptive of an entire group or class; general. !! 2. Biology Of or relating to a genus. !! 3.a. Not having a brand name: generic soap. !! b. Of or being a drug sold under or identified by its official nonproprietary or chemical name. !! 4. Grammar Specifying neither masculine nor feminine gender:
!!
C++ for C Programmers by Ira Pohl
Generic Programming
!!
Writing code that can use an arbitrary type or types; in C++ this is done with template
Consider writing a function that sums an array. Assume that most of time you want the sum to start with zero, but sometimes you want a different initial value.
Sum an array
template <class T> //T is generic type !! T sum(const T data[], int size, T s=0) !! { !! for(int i = 0; i < size; ++i) !! s += data[i]; //+= must work for T !! return s; !! }
!!
Default parameter
T sum(const T data[], int size, T s=0) !! Ideas data is not mutable use a const !! s will default to 0
!!
sum(scores, 92); !! sum(scores, 92, 58); !! Same function two different signatures !! Note could also default size; think about it
!!
C++ for C Programmers by Ira Pohl \
C++ Program
int main() !! { !! cout << "template for sum()" << endl; !! int a[] = {1, 2, 3}; !! double b[] = {2.1, 2.2, 2.3}; !! cout << sum(a, 3) << endl; !! cout << sum(b, 3) << endl; !! }
!!
C++ for C Programmers by Ira Pohl
C++ Program
Elements of the array source are not be modified . !! Simple parameters, such as size, are typically call by value and can not be modified by the calling routine.
!! !!
Iterate subtraction over the data Write a template function that outputs the elements of the array
!!
Answer
for(int i = 0; i < size; ++i) !! s -= data[i]; //+= used for sum
!!
for(int i = 0; i < size; ++i) !! cout << data[i] << \t; !! //you can make this prettier
!!
have used templates with one template parameter, but it is useful to have more that one distinct type in a template. !! More genericity but be careful!!
C++ templates
template<class T1, class T2> !! void copy(const T1 source[], T2 destination[], int size) !! { !! for(int i = 0; i < size; ++i) !! destination[i] = !! static_cast<T1>( source[i]); !! }
!!
C++ Casts
!! More
types means worrying about conversions and more signatures !! These static_cast operators are considered safe. !! The old cast operator (type) is deprecated As a reminder the other casting operators are: !! reinterpret_cast<type> highly unsafe !! dynamic_cast<type> used with classes !! const_cast<type> cast away const-ness
4 nodes
Answer K4
!!
!!
Graphs
!! The
Seven Bridges of Knigsberg is a historically notable problem in mathematics. Leonhard Euler in 1735 laid the foundations of graph theory examining this problem.
7 Bridges Problem
Koningsberg
!!
!!
!!
The city of Knigsberg in Prussia (now Kaliningrad, Russia) was set on both sides of the Pregel River, and included two large islands which were connected to each other and the mainland by seven bridges. The problem was to find a walk through the city that would cross each bridge once and only once. The islands could not be reached by any route other than the bridges, and every bridge must have been crossed completely every time; one could not walk halfway onto the bridge and then turn around and later cross the other half from the other side. Euler proved that the problem has no solution. There could be no non-retracing continuous curve that passed through all seven of the bridges..
!! Edge
!! Tradeoffs
List representation
Definition: A representation of a directed graph with n vertices using an array of n lists of vertices.
!!
!! List
undirected graph may be represented by having vertex j in the list for vertex i and vertex i in the list for vertex j.
C++ for C Programmers by Ira Pohl
1 2 3 4
!!
My drawing
Quiz
Here is an undirected graph generate an edge list representation and a matrix representation for it. !! o !! | !! o ___ o ___ o !! | !! o
!!
C++ for C Programmers by Ira Pohl
Answer Matrix
!!
1 2 !! 3 4 5
!!
Step 1 - include s in a closed set and all immediate successors of s with their distance in the open set !! Step 2 - pick the open node of list cost- say this node is n
!!
C++ for C Programmers by Ira Pohl
Dijkstra
If the node that is picked is d stop !! Otherwise compute all succesors of n; !! Add the distance from s to n + n edge to k !! And if it improves on value in open set store as new value !! Pick current open set distance that is a min and repeat above steps.
!!
Dijkstra Termination
If the node that is picked is d stop !! No more succesors failed no path !! A shortest path tree should be maintained that lets you create the route
!!
1.!
!! !!
Point as an example
Quiz
!!
If you have the expression 3 / 4 what is its value? !! If you have the expression 3.0 / 4 what is its value?
!!
Answers
Any of short, int , double, char, long, long double, int* !! 3 / 4 both int literals answer 0 !! 3.0 / 4 double / int double division 0.75
!! !!
Enum is a simple int type Typedef enum color{RED, WHITE,GREEN} color; RED is defaulted to 0. WHITE is 1 and GREEN is 2
!!
!!
Answer
A) Can use a named const integer so it is redundant? Okay
!!
Example: days
!!
typedef enum days{SUN, MON, TUE, WED, THU, FRI, SAT} days; inline days operator+ (days d){ return static_cast<days>((static_cast<int>(d) + 1) % 7); }
!! !! !! !!
ostream& operator<< (ostream& out, days d){ switch (d){ case SUN: out << "SUN"; break; case MON: out << "MON"; break; } return out; } //operator << is normally left bit shift
!!
Example Days
!! !! !! !! !! !!
int main() { days d = MON, e; e = +d; cout << d << '\t' << e << endl; }
Quiz
!!
What native operator is << ? Can its precedence be changed ? How do we know which meaning to apply?
!!
!!
Answer
!!
!!
!!
Types are related to domains So when you need to talk about widgets-you want the widget type and actions on widgets C had primitive forms of type extensibility
!!
!!
C Type Extension
!! !!
In C you can add a type using struct. In C++ struct is different struct is a named scope that can include functions (methods) and have different layers of opacity (data hiding). While C++ retains struct it has the new keyword class. Class is almost equivalent to struct but with different data hiding defaults.
!!
typedef struct point{double x, y;} point; void add_points(point* p1, point* p2, point* sum){ sum->x = p1->x + p2->x; sum->y = p1->y + p2->y; }
C struct
!!
Struct has fields data members File scope functions manipulate the struct using pointer operations
!!
C++ point
class point{ !! public: !! double x, y; !! };
!! !!
Better Point
!! !! !! !! !! !! !! !!
class point{ public: double getx(){return x;} void setx(double val){x = v;} .. private: double x, y; };
Q : Review OO
!!
Answer
!!
The principle of the black box what is under the hood should be left to experts; This includes representation.
!!
Point functions
!! !! !! !! !! !! !! !! !!
point operator+ (point& p1, point& p2){ point sum = {p1.x + p2.x, p1.y + p2.y}; return sum; } ostream& operator<< (ostream& out, point& p){ out << "( " << p.x << ", " << p.y <<" )"; return out; } .
C++
int main() !! { !! point a = {3.5, 2.5}, b = {2.5, 4.5}, c; !! cout << "a = " << a << " b = " << b <<endl; !! cout << " sum = " << a + b << endl; !! }
!!
Using point in main() looks very much like using a native type. Indeed this is one of our key goals in OO. We accomplished this by having point be a class -a user defined type. We overload the standard operators like + and << to give them appropriate "point semantics.
!!
!!
Methods
class point{ !! public: !! double getx(){return x;} !! void setx(double val){x = v;} !! Class member functions have automatic access to private members. !! p1.getx() p2.setx(2.5) p2.sety(-1.8)
!!
Object construction is needed for OO Built in objects such as int double, fixed arrays are built by the compiler. Big part of OO/C++ mastery is how to build objects :
!!
!!
point(){ x = y = 0.0;}
Finally
!!
Constructors and destructors are our next major topic in reading chapter 5 To be continued.
!!