CSS 342 Data Structures, Algorithms, and Discrete Mathematics I

Slides:



Advertisements
Similar presentations
Class and Objects.
Advertisements

J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Templates and Polymorphism Generic functions and classes.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Data Structures Using C++1 Chapter 2 Object-Oriented Design (OOD) and C++
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
Case Study - Fractions Timothy Budd Oregon State University.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CH1, C++ INTERLUDE 1.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE C++ INTERLUDE 1.3. C++ BOOK.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CH 2, APPENDIX E.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
Chapter 11 Friends and Overloaded Operators. Introduction to function equal // Date.h #ifndef _DATE_H_ #define _DATE_H_ class CDate { public: CDate();
1 Today’s Objectives  Announcements Homework #3 is due on Monday, 10-Jul, however you can earn 10 bonus points for this HW if you turn it in on Wednesday,
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
1 CSC 222: Computer Programming II Spring 2004 Pointers and dynamic memory  pointer type  dereference operator (*), address-of operator (&)  sorting.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 5 1.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO , APP D, C++ BOOK.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Learning Objectives Fundamentals of Operator Overloading. Restrictions of Operator Overloading. Global and member Operator. Overloading Stream-Insertion.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO C++ INTERLUDE 2, CHAPT 4, 6.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
Operator Overloading.
Andy Wang Object Oriented Programming in C++ COP 3330
Yan Shi CS/SE 2630 Lecture Notes
Motivation for Generic Programming in C++
“Generic Programming” ECE 297
Strings: C-strings vs. Strings as Objects
C++ Templates.
Template Classes and Functions
Introduction to C++ Systems Programming.
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
References as Function Arguments
Object-Oriented Design (OOD) and C++
A First C++ Class – a Circle
Dr. Bernard Chen Ph.D. University of Central Arkansas
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
A Lecture for the c++ Course
Homework 4 questions???.
CSC113: Computer Programming (Theory = 03, Lab = 01)
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
The dirty secrets of objects
group work #hifiTeam
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
3.3 Abstract Classes, Assignment, and Casting in a Hierarchy
Operator Overloading; String and Array Objects
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Strings: C-strings vs. Strings as Objects
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
Advanced Program Design with C++
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Constructors and Other Tools
Operator Overloading.
CISC/CMPE320 - Prof. McLeod
COP 3330 Object-oriented Programming in C++
COMS 261 Computer Science I
Recitation Course 0603 Speaker: Liu Yu-Jiun.
Operator Overloading; String and Array Objects
IT533 Adapted from Textbook (SAVITCH) and Lecture Notes (PUSATLI), 2014.
CMSC 341 C++ and OOP.
CMSC 202 Lesson 6 Functions II.
Lists CMSC 202, Version 4/02.
Class rational part2.
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Lists CMSC 202, Version 4/02.
CMSC 341 C++ and OOP.
An Introduction to STL.
Presentation transcript:

CSS 342 Data Structures, Algorithms, and Discrete Mathematics I Lecture 4. 161011. C++ Interlude 1.3, 5. C++ Book.

Announcements / Agenda Homework due: Tomorrow! Quiz: Move to 10/20 Study Groups? Program 2 assigned Agenda: Finish operating overloading C++ Templates: functions and class Examples: Vector, Swap, Bubble Sort, Insertion Sort Added Bonus if time permitting: Arrays, Pointers, Object lifetimes.

Operator Overloading Allowing for operators to work on classes in intuitive ways. Key Examples: Arithmetic: +, -, *, / Comparison: ==, !=, <, >, <=, >= Input: <<, >> General rules for overloading Whenever the meaning of an operator is not obviously clear and undisputed, it should not be overloaded Always stick to the operator’s well-known semantics Always provide all out of a set of related operations Operators retain their precedence order

Overloading +,-,*,/ as member functions class Rational { public: // Op Overloads Rational operator*(const Rational &rat) const; Rational operator/(const Rational &rat) const; Rational operator-(const Rational &rat) const; Rational operator+(const Rational &rat) const; };

Overloading +=,-=,*=,/= as member functions class Rational { public: // Op Overloads Rational operator*=(const Rational &rat); Rational operator/=(const Rational &rat); Rational operator-=(const Rational &rat); Rational operator+=(const Rational &rat); };

But wait… Given we overloaded +, is there a better way to implement +=? Actually, one should implement += first, and then used it to implement + Same for -=/-, *=/*, and / /=

Using += overload to implement + MyClass & MyClass::operator+=(const MyClass &rhs) { ... // Do the compound assignment work. return *this; } MyClass MyClass::operator+(const MyClass &other) const MyClass result = *this; result += other; return result;

Overloading input/output <<, >> class Rational { public: friend ostream& operator<<(ostream &outStream, const Rational &rat); friend istream& operator>>(istream &inStream, Rational &rat); // Op Overloads Rational operator*(const Rational &rat) const; Rational operator/(const Rational &rat) const; Rational operator-(const Rational &rat) const; Rational operator+(const Rational &rat) const;

Implementation of <<, >> overloads ostream& operator<<(ostream &outStream, const Rational &rat) { outStream << rat.numerator << "/" << rat.denominator; return outStream; } istream& operator>>(istream &inStream, Rational &rat) inStream >> rat.numerator >> rat.denominator; if (rat.denominator == 0) rat.numerator = 0; rat.denominator = 1; else rat.reduce(); return inStream;

Overloading ==, !=, +=, etc… class Rational { friend ostream& operator<<(ostream &outStream, const Rational &rat); friend istream& operator>>(istream &inStream, Rational &rat); public: // Op Overloads Rational operator*(const Rational &rat) const; Rational& operator*=(const Rational &rat); Rational operator/(const Rational &rat) const; Rational& operator/=(const Rational &rat); Rational operator-(const Rational &rat) const; Rational& operator-=(const Rational &rat); Rational operator+(const Rational &rat) const; Rational& operator+=(const Rational &rat); bool operator==(const Rational &rat) const; bool operator!=(const Rational &rat) const;

Implementation bool Rational::operator==(const Rational &rat) const { return((numerator == rat.numerator) && (denominator == rat.denominator)); } bool Rational::operator!=(const Rational &rat) const return ((numerator != rat.numerator) || (denominator != rat.denominator)); bool Rational::operator<(const Rational &rat) const return ((numerator * rat.denominator) < (rat.numerator * denominator)); bool Rational::operator<=(const Rational &rat) const return ((numerator * rat.denominator) <= (rat.numerator * denominator)); bool Rational::operator>(const Rational &rat) const return ((numerator * rat.denominator) > (rat.numerator * denominator)); bool Rational::operator>=(const Rational &rat) const return ((numerator * rat.denominator) >= (rat.numerator * denominator));

Resources on overloading. http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html http://courses.washington.edu/css342/dimpsey/ProgramExamples/code.html -- rational class

Vectors

Vectors #include <vector> #include <iostream> using namespace std; int main() { vector<int> first;//empty vector vector<int> second = {100, 200, 300};//vector of 100,200,300 vector<int> third = second;//copy of second vecotry vector<int> fourth(4, 100);//vector of 4, 100s second.push_back(400); for (int i = 0; i < second.size(); i++) cout << "val[" << i << "] = " << second[i] << endl; cout << "val[" << i << "] = " << second.at(i) << endl; } return 0;

Vectors Excellent data structure choice Fast, safe-access, good memory characteristics Built on dynamic array Templatized so that vector<myFooClass> vFoo(4, foos); vector<Bird> birds(3, eagle);

Vector with user defined objects #include "Bird.h" #include <vector> #include <string> #include <iostream> using namespace std; int main() { Bird b1("duck"); Bird b2("goose"); vector<Bird> birds; //empty vecotor of birds vector<Bird> birds2(4, b1);//4 ducks birds2.push_back(b2); for (int i = 0; i < birds2.size(); i++) cout << birds2.at(i).getName() << endl; } return 0;

Who really developed the Von Neumann architecture? CSS430 Operating Systems : Introduction

Templates One Function works on ALL types!

Templates Polymorphism Works on Function or Class level Allows for multiple types to be passed to function or class One set of code works across all types Works on Function or Class level Syntax: template <class ItemType> ItemType is the type utilized throughout code Function/Class must be able to handle the types utilized

Why Object Oriented Programming (OOP)? Abstraction Encapsulation Hierarchy Polymorphism

Templatize Function SWAP

Swap (w/doubles) int main() void SwapInt(double &a, double &b) { { cout << "a = " << a << " b = " << b << endl; SwapInt(a, b); cin >> a; return 0; } void SwapInt(double &a, double &b) { int temp; temp = a; a = b; b = temp; return; }

Swap<> template<class ItemType> int main() { int a = 3; int b = 1000000; Swap(a, b); cout << a << endl; string nameA = "ChapoGuzman"; string nameB = "JimmyHoffa"; Swap(nameA, nameB); cout << nameA << endl; return 0; } template<class ItemType> void Swap(ItemType &x, ItemType &y) { ItemType temp = x; x = y; y = temp; }

Templatize Class SORTED LIST

SortedList Class Template Example Example to show templates on a class which keeps a sorted set of items Add an item Print out items Sort Bonus Points: concatenate two lists Data Structure: Vector Sorts BubbleSort Insertion sort algorithm

#ifndef SORTED_LIST_H #define SORTED_LIST_H #include <iostream> #include <vector> using namespace std; template <class ItemType> class SortedList { public: SortedList(); ~SortedList(); void Add(const ItemType &item); void Print() const; void Sort(); private: vector<ItemType> thelist; }; #include "SortedList.cpp" #endif #ifndef SORTED_LIST_CPP #define SORTED_LIST_CPP #include "SortedList.h" template<class ItemType> SortedList<ItemType>::SortedList(){ } void SortedList<ItemType>::Add(const ItemType &item) { thelist.push_back(item); return; } void SortedList<ItemType>::Print() const for (int i = 0; i < thelist.size(); i++) cout << thelist[i] << endl; #endif

Class Bell

Bubblesort or Sinking Sort Used to sort an array of items by traversing (n-1) times and bubbling largest current item to the bottom Graphical Representation : http://en.wikipedia.org/wiki/Bubble_sort#mediaviewer/File:Bubble-sort- example-300px.gif Bad memory and speed characteristics. “the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems“, Donald Knuth

Insertion Sort Sorted Unsorted Copy 10 Shift 29 Insert 10, copy 14 37 13 Copy 10 Shift 29 29 29 14 37 13 10 29 14 37 13 Insert 10, copy 14 unsortedTop 10 29 29 37 13 Shift 29 10 14 29 37 13 Insert 14; copy 37 10 14 29 37 13 Shift nothing 10 14 29 37 13 Insert 37; Copy 13 10 14 14 29 37 Shift 37, 29 and 14. 10 13 14 29 37 Insert 13 Or Carranno 311-313, Or: http://en.wikipedia.org/wiki/Insertion_sort#mediaviewer/File:Insertion-sort-example-300px.gif

Function for Insertion Sort template<class ItemType> void SortedList<ItemType>::Sort() { for (int place = 1; place < thelist.size(); place++) ItemType temp = thelist[place]; int i = place; while ((i > 0) && (thelist[i-1] > temp)) thelist[i] = thelist[i-1]; i--; } thelist[i] = temp;

C++ Fundamentals

Pointers 4 3 1 5 Pointer variables int *p, *q; Static allocation int x; Address-of operator p = &x; Memory cell to which P points *p = 6; Pointer operations q = p; 4 3 1 ? p q x ? p q x ? 6 p q x 5 6 p q x

Arrays Arrays: reservation and construction of indexed set of objects or built-in types int x=5; int arr1[100] int arr2[3] = {34, 7, 34}; char cArr1[7]; char cArr2[10][5]; arr1[x] = 32; arr2[0] = arr1[x]; cArr2[3][3] = ‘a’; Arrays v Pointers (following are equivalent) void Foo(int arr[]) { } void Foo(int *arr) { } MyFooClass theFooObj; MyFooClass arrFoo[200]; //default constructors run MyFooClass *pFoo; pFoo = arrFoo; arrFoo[54] = theFooObj; pFoo = &theFooObj;

Time of Invocation (constructors) Automatic Local Each time block is executed Static Local Once –first time it is hit Global In order of declaration in translation unit Typically before main() is entered Destroyed in reverse order of construction Dynamic (tbd) malloc/free new/delete