CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE 4. 150114. C++ INTERLUDE 1.3. C++ BOOK.

Slides:



Advertisements
Similar presentations
C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables.
Advertisements

CSCI 160 Midterm Review Rasanjalee DM.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
CIS 101: Computer Programming and Problem Solving Lecture 8 Usman Roshan Department of Computer Science NJIT.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Review of pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Review of C++ Programming Part II Sheng-Fang Huang.
Java and C++, The Difference An introduction Unit - 00.
1 CSC 222: Computer Programming II Spring 2004 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search Class design  templated.
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CARRANO CH ; CUSACK CH 8: OPTIONAL.
Lecture DS & Algorithms:09 Abstract Data Types. Lecture DS & Algorithms:09 2 Abstract Data Types Data Type: A data type is a collection of values and.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
ITEC 320 C++ Examples.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 5 An Array Class Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
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.
Templates Mark Hennessy Dept Computer Scicene NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO CH 2, APPENDIX E.
CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account sysadmin/account_request.cgi Need to know UNIX (Linux)
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
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,
CSS 332 PROGRAMMING ISSUES WITH OBJECT-ORIENTED LANGUAGES LECTURE
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
1 CSC 222: Computer Programming II Spring 2004 Pointers and dynamic memory  pointer type  dereference operator (*), address-of operator (&)  sorting.
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.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
11 Introduction to Object Oriented Programming (Continued) Cats.
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Introduction to Object Oriented Programming Chapter 10.
CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE CARRANO C++ INTERLUDE 2, CHAPT 4, 6.
CSS342: Introduction1 Professor: Munehiro Fukuda.
Chapter 2 Creating a C++ Program. Elements of a C++ Program Four basic ways of structuring a program Four basic ways of structuring a program 1.Sequencing.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
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.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
Objectives You should be able to describe: One-Dimensional Arrays
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
1 Chapter 12 Classes and Abstraction. 2 Chapter 12 Topics Meaning of an Abstract Data Type Declaring and Using a class Data Type Using Separate Specification.
Chapter 12 Classes and Abstraction
Andy Wang Object Oriented Programming in C++ COP 3330
Introduction to C++ Systems Programming.
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Homework 4 questions???.
CSC113: Computer Programming (Theory = 03, Lab = 01)
C Basics.
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.
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
CSS 342 Data Structures, Algorithms, and Discrete Mathematics I
Andy Wang Object Oriented Programming in C++ COP 3330
foo.h #ifndef _FOO #define _FOO template <class T> class foo{
Today’s Objectives 28-Jun-2006 Announcements
CMSC 341 C++ and OOP.
Presentation transcript:

CSS 342 DATA STRUCTURES, ALGORITHMS, AND DISCRETE MATHEMATICS I LECTURE C++ INTERLUDE 1.3. C++ BOOK.

Announcements Agenda: C++ Templates: functions and class Examples: Vector, Swap, Bubble Sort, Insertion Sort Review Assignment 2 Time Permitting: Object lifetimes, Arrays, Pointer Review

Vectors #include Using namespace std; main () { vector first; // empty vector of ints vector second (4,100); // four ints with value 100 vector third (second.begin(),second.end()); // iterating through second vector fourth (third); // a copy of third for (int i=0; i < second.size(); i++) { cout << second.at(i); cout << second[i]; } second.push_back(56); second.pop_back(); }

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

#include "Bird.h" #include int main() { Bird b1("eagle"); Bird b2 = b1; vector birds; vector birds2(4, b2); vector birds3(birds2); birds2.push_back(Bird("penguin")); for (int i = 0; i < birds2.size(); i++) { cout << birds2[i].getName() << endl; } return 0; }

Templates Polymorphism 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 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

Let’s templatize a function

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

template void swapAll(ItemType &, ItemType &); int main() { double aDouble = 3, bDouble = 7; int aInt = 5, bInt = 13; string aString("First"), bString("Second"); cout << "aDouble = " << aDouble << " bDouble = " << bDouble << std::endl; swapAll(aDouble, bDouble); cout << "aDouble = " << aDouble << " bDouble = " << bDouble << std::endl; cout << "aInt = " << aInt << " bInt = " << bInt << endl; swapAll(aInt, bInt); cout << "aInt = " << aInt << " bInt = " << bInt << endl; cout << "aString = " << aString << " bString = " << bString << endl; swapAll(aString, bString); cout << "aString = " << aString << " bString = " << bString << endl; return 0; } template void swapAll(ItemType &a, ItemType &b) { ItemType temp; temp = a; a = b; b = temp; return; } Swap w/Templates

Computer Scientist of the week Grace Hopper Invented the first compiler United States Navy Rear Admiral Promoted the idea of machine independent languages Key inventor of COBOL Popularized the term debugging Advocated for Navy to move from centralized computers to distributed computers in the 1970s

Let’s templatize a class SORTED SET OF ITEMS

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 Sort Will show BubbleSort and Insertion sort algorithm

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

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 : example-300px.gif 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 SortedUnsorted Copy 10 Shift 29 Insert 10, copy 14 Shift 29 Insert 14; copy 37 Insert 37; Copy 13 Shift 37, 29 and 14. Insert Shift nothing unsortedTop Or Carranno , Or:

template void SortedList ::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; } Function for Insertion Sort

Review Assignment 2

C++ Fundamentals

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

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;

File IO In C:In C++:In Java: FILE *fp;ifstream inFile(“name.dat”);import java.io.*; FileInputStream infile = istream inFile;new FileInputStream( “name.dat” ); if ((fp = fopen( “name.dat”, “r” ))inFile.open(“name.dat”);ObjectInputStream input = != NULL {if ( inFile ) { // true of falsenew ObjectInputStream( infile ); fscanf( fp, “%d”, &i );inFile >> i;try { i = input.readInt( ); fclose(fp);inFile.close( );} catch ( EOFException e ) { }}input.close( ); } Note: for output, use ofstream.

example.h #ifndef EXAMPLE_H #define EXAMPLE_H Full.h file #endif

Dynamic Allocation 1. Pointer declarationint *p, *q; 2. Dynamic allocationp = new int; q = new int; 3. Deallocationdelete p; p = NULL; 4. Memory leakq = new int; ? ? ? p q p q p q p q ??? ? NULL Leak!

Dynamic Allocation Works with all Object types Bird *pBigBird pBigBird = Bird(“chicken”); string s = pBigBird->species;