Programming Abstraction in C++

Similar documents
การทดลองท 8_2 Editor Buffer Array Implementation

Dynamic Data Structures

About this exam review

Practice Final Examination #2

CPSC 427: Object-Oriented Programming

Solution for Data Structure

! A data structure representing a list. ! A series of nodes chained together in sequence. ! A separate pointer (the head) points to the first

! A data structure representing a list. ! A series of dynamically allocated nodes. ! A separate pointer (the head) points to the first

Short Notes of CS201

CS 215 Fundamentals of Programming II Spring 2018 Project 5

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

CS201 - Introduction to Programming Glossary By

Constants, References

List: Tree: Students are expected to pay attention and fill in the details. Fundamental dynamic memory structure is: list

15-122: Principles of Imperative Computation, Spring Due: Thursday, March 10, 2016 by 22:00

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

Linked Lists. Gaddis Ch. 17. CS 2308 :: Spring 2016 Molly O'Neil

1 Deletion in singly linked lists (cont d) 1 Other Functions. 1 Doubly Linked Lists. 1 Circular lists. 1 Linked lists vs. arrays

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

CPSC 427: Object-Oriented Programming

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

C++ - Lesson 2 This is a function prototype. a' is a function that takes an integer array argument and returns an integer pointer.

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Pointers and References

CSCE 110 PROGRAMMING FUNDAMENTALS

Programming Abstraction in C++

Linked Lists

Lecture 15a Persistent Memory & Shared Pointers

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19

5 Phases of Software Life Cycle

FORM 2 (Please put your name and form # on the scantron!!!!)

And Even More and More C++ Fundamentals of Computer Science

CSE 509: Computer Security

CS201 Some Important Definitions

CMSC 341 Lecture 7 Lists

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

CSC 533: Organization of Programming Languages. Spring 2005

Consider the program...

Lecture 07 Heap control data. Stephen Checkoway University of Illinois at Chicago

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Programming Abstraction in C++

Containers: Queue and List. Jordi Cortadella and Jordi Petit Department of Computer Science

Pointers, Dynamic Data, and Reference Types

Review for Test 1 (Chapter 1-5)

Starting Savitch Chapter 10. A class is a data type whose variables are objects. Some pre-defined classes in C++ include int,

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Linked List using a Sentinel

Dynamic Allocation of Memory

Midterm Practice TA: Brian Choi Section Webpage:

PART - I 75 x 1 = The building blocks of C++ program are (a) functions (b) classes (c) statements (d) operations

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

CS 106X, Lecture 16 More Linked Lists

Processes. OS Structure. OS Structure. Modes of Execution. Typical Functions of an OS Kernel. Non-Kernel OS. COMP755 Advanced Operating Systems

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Classes and Pointers: Some Peculiarities

7.1 Optional Parameters

COMP 11 Class 17 Outline

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

BBM 201 DATA STRUCTURES

CPSC 427: Object-Oriented Programming

05-01 Discussion Notes

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

malloc() is often used to allocate chunk of memory dynamically from the heap region. Each chunk contains a header and free space (the buffer in which

Queue Implementations

Data Structures. Lecture 04 Sohail Aslam AL 1

CS32 - Week 2. Umut Oztok. July 1, Umut Oztok CS32 - Week 2

CS201- Introduction to Programming Current Quizzes

The University of British Columbia

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

CSC1322 Object-Oriented Programming Concepts

Practice Final Examination #2

Midterm Exam. Sample Solutions

Computer Programming

Review Questions for Final Exam

CSCI 102L - Data Structures Midterm Exam #2 Spring 2011

COMP 2355 Introduction to Systems Programming

Topic Binary Trees (Non-Linear Data Structures)

Name: I. 20 II. 20 III. 20 IV. 40. CMSC 341 Section 01 Fall 2016 Data Structures Exam 1. Instructions: 1. This is a closed-book, closed-notes exam.

Classes, Constructors, etc., in C++

Sequential Containers Cont'd

CSE au Midterm Exam Nov. 2, 2018 Sample Solution

EE 355 Unit 11b. Doubly-Linked Lists and Deques. Mark Redekopp

Wentworth Institute of Technology COMP201 Computer Science II Spring 2015 Derbinsky. Stacks and Queues. Lecture 11.

Programación de Computadores. Cesar Julio Bustacara M. Departamento de Ingeniería de Sistemas Facultad de Ingeniería Pontificia Universidad Javeriana

Padasalai.Net s Model Question Paper

CP2 Revision. theme: dynamic datatypes & data structures

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Elementary Data Structures: Part 1: Arrays, Lists. CSE 2320 Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington

Comp Sci 1MD3 Mid-Term II 2004 Dr. Jacques Carette

Unit 4 Basic Collections

SRI SARASWATHI MATRIC HR SEC SCHOOL PANAPAKKAM +2 IMPORTANT 2 MARK AND 5 MARK QUESTIONS COMPUTER SCIENCE VOLUME I 2 MARKS

Ch. 11: References & the Copy-Constructor. - continued -

CSE 333 Midterm Exam 5/9/14 Sample Solution

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Practical C++ Programming

Tokens, Expressions and Control Structures

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Transcription:

Programming Abstraction in C++ Eric S. Roberts and Julie Zelenski Stanford University 2010

Chapter 10. Efficiency and Data Representation

Outline 1 An Editor Buffer 2 Implementation I: Character Array 3 Implementation II: Stacks 4 Implementation III: Linked List

Outline 1 An Editor Buffer 2 Implementation I: Character Array 3 Implementation II: Stacks 4 Implementation III: Linked List

Introduction Goal Use editor buffer as an example to illustrate how the choice of data representation affects the efficiency of applications. Method Use a low-level built-in structure, such as character array, so the operations are visible and thus easier to assess efficiency. Lesson Find options and evaluate the trade-offs. A good design demands compromise. Important The external behavior of an editor buffer (Table 10-1, p. 340) must remain the same while implementation changes.

Operations Move the cursor forward one position movecursorforward() Move the cursor backward one position movecursorbackward() Jump the cursor to the beginning (before the first character) movecursortostart() Move the cursor to the end (after the last character) movecursortoend() Insert a character at the current cursor position insertcharacter(char ch) Delete the character just after the cursor position deletecharacter() Desplay the content of the buffer display()

Interface design Constructor EditorBuffer() Destructor EditorBuffer()

Interface design Constructor EditorBuffer() Destructor EditorBuffer() Commands: F: move forward B: move backward J: jump to beginning E: jump to end Ixxx: insert characters xxx D: delete Q: quit editor

Interface design (cont.) The interface, the public section, Figure 10-1, p. 343-344. Study Documentation Style (boilerplate, class definition) The public method prototypes The private section is included from a file bufpriv.h

Interface design (cont.) The interface, the public section, Figure 10-1, p. 343-344. Study Documentation Style (boilerplate, class definition) The public method prototypes The private section is included from a file bufpriv.h Now that you have the interface, you can write an application program solely based on it, without knowing the implementation. The application program should not be affected when implementation changes.

Command-driven editor Figure 10-2, p. 346 Pattern: command-driven editor int main() { EditorBuffer buffer; while (true) { cout << "*"; string cmd = GetLine(); if (cmd!= "") ExecuteCommand(buffer, cmd); buffer.display(); return 0;

Command-driven editor Figure 10-2, p. 346 Pattern: command-driven editor int main() { EditorBuffer buffer; while (true) { cout << "*"; string cmd = GetLine(); if (cmd!= "") ExecuteCommand(buffer, cmd); buffer.display(); return 0; A shell program is similar.

Command-driven editor (cont.) void ExecuteCommand(EditorBuffer & buffer, string line) { switch (toupper(line[0]) { case I : for (int i = 1; i < line.length(); i++) { buffer.insertcharacter(line[i]); break; case D : buffer.deletecharacter(); break; case F : buffer.movecursorforward(); break; case B : buffer.movecursorbackward(); break; case J : buffer.movecursortostart(); break; case E : buffer.movecursortoend(); break; case Q : exit(0); default: cout << "Illegal command" << endl; break;

Outline 1 An Editor Buffer 2 Implementation I: Character Array 3 Implementation II: Stacks 4 Implementation III: Linked List

Private data representation Buffer A character array of fixed capacity, which can be extended like the dynamic CharStack. Current length of the buffer. cursor Position, the index of the character that immediately follows the cursor.

Private data representation Buffer A character array of fixed capacity, which can be extended like the dynamic CharStack. Current length of the buffer. cursor Position, the index of the character that immediately follows the cursor. Private instance variables: char *array; int capacity; int length; int cursor;

Implementing the methods Moving cursor operations are straightforward. Constructor and destructor, Figure 10-3, p. 349 EditorBuffer::EditorBuffer() { capacity = INITIAL_CAPACITY; array = new char[capacity]; length = 0; cursor = 0; EditorBuffer:: EditorBuffer() { delete[] array;

movecursortoend void EditorBuffer::moveCursorToEnd() { cursor = length; The size of the array must be at least length + 1.

Insertion buffer.insertcharacter( X ); Before array capacity length cursor 15 5 3 H E L L O 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Insertion (cont.) buffer.insertcharacter( X ); After array capacity length cursor 15 6 4 H E L X L O 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Insertion (cont.) Figure 10-3, p. 350 void EditorBuffer::insertCharacter(char ch) { if ((length + 1) == capacity) expandcapacity(); for (int i = length; i > cursor; i--) { array[i] = array[i - 1]; array[cursor] = ch; length++; cursor++; expandcapacity (p. 351) is similar to CharStack counterpart (p.326).

Insertion (cont.) Figure 10-3, p. 350 void EditorBuffer::insertCharacter(char ch) { if ((length + 1) == capacity) expandcapacity(); for (int i = length; i > cursor; i--) { array[i] = array[i - 1]; array[cursor] = ch; length++; cursor++; expandcapacity (p. 351) is similar to CharStack counterpart (p.326). deletecharacter (p. 350) is similar.

Assessing complexity Problem size N: buffer length Operation count: The operations (comparison, addition, assignment) in moving the cursor are independent of N (constant). No loops.

Assessing complexity The operations of copying characters (assignment) in insertion and deletion are dependent of the buffer length. A loop. In the worst cases, inserting a character in the beginning or deleting a character in the beginning requires copying the entire buffer. void EditorBuffer::insertCharacter(char ch) { if ((length + 1) == capacity) expandcapacity(); for (int i = length; i > cursor; i--) { array[i] = array[i - 1]; array[cursor] = ch; length++; cursor++;

Assessing complexity (cont.) Function movecursorforward movecursorbackward movecursortostart movecursortoend insertcharacter deletecharacter Complexity O(1) O(1) O(1) O(1) O(N) O(N) Note. When we do a lot of insertions and deletions and the buffer is large, it gets slow.

Outline 1 An Editor Buffer 2 Implementation I: Character Array 3 Implementation II: Stacks 4 Implementation III: Linked List

Using stacks Idea: Breaking the buffer at the cursor boundary. Two stacks: One contains the characters that precede the cursor; One contains the characters after the cursor. H E L L O L E H before L O after

Using stacks Idea: Breaking the buffer at the cursor boundary. Two stacks: One contains the characters that precede the cursor; One contains the characters after the cursor. H E L L O L E H before L O after Private data representation CharStack before; CharStack after;

Implementing the methods Figure 10-4, pp. 355-356 void EditorBuffer::moveCursorForward() { if (!after.isempty()) { before.push(after.pop()); movecursorbackward is similar. No loops.

Implementing the methods Figure 10-4, pp. 355-356 void EditorBuffer::deleteCharacter() { if (!after.isempty()) { after.pop(); insertcharacter is similar. No loops.

Implementing the methods (cont.) movecursortostart requires a loop. void EditorBuffer::moveCursorToStart() { while (!before.isempty() { after.push(before.pop()); Worst case: When the cursor is currently at the end, we have to move (assignment) the entire buffer.

Implementing the methods (cont.) movecursortostart requires a loop. void EditorBuffer::moveCursorToStart() { while (!before.isempty() { after.push(before.pop()); Worst case: When the cursor is currently at the end, we have to move (assignment) the entire buffer. movecursortoend is similar. A loop.

Assessing complexity Table 10-3, p. 354. Function movecursorforward movecursorbackward movecursortostart movecursortoend insertcharacter deletecharacter Complexity O(1) O(1) O(N) O(N) O(1) O(1)

Outline 1 An Editor Buffer 2 Implementation I: Character Array 3 Implementation II: Stacks 4 Implementation III: Linked List

Linked list What is a linked list? Linked by what?

Linked list What is a linked list? Linked by what? A list of cells linked by pointers.

Cell structure The structure of a cell: struct cellt { char ch; cellt *link; A recursive type.

Private data struct cellt { char ch; cellt *link; ; cellt *start; cellt *cursor; Use the special pointer value NULL to signify the end of a list. Use a dummy cell at the beginning of a list. (Why?)

Constructor EditorBuffer::EditorBuffer() { // initialize dummy cell start = new cellt; start->link = NULL; // initialize cursor cursor = start; start cursor A dummy cell.

Example A B C start cursor A B C The cursor pointer points to the cell containing the character that immediately precedes the cursor.

Simple things first void EditorBuffer::moveCursorForward() { if (cursor->link!= NULL) { cursor = cursor->link; void EditorBuffer::moveCursorToStart() { cursor = start; start cursor A B C

Move the cursor backward Search from the start for the pointer pointing to the cell whose link field equals cursor. EditorBuffer::moveCursorBackward() { cellt *cp = start; if (cursor!= start) { while (cp->link!= cursor) { cp = cp->link; cursor = cp; Requires a loop.

Move the cursor backward (cont.) EditorBuffer::moveCursorBackward() { cellt *cp = start; if (cursor!= start) { while (cp->link!= cursor) { cp = cp->link; cursor = cp; start cursor cp

Move the cursor backward (cont.) EditorBuffer::moveCursorBackward() { cellt *cp = start; if (cursor!= start) { while (cp->link!= cursor) { cp = cp->link; cursor = cp; start cursor cp

Move the cursor to the end movecursortoend is similar to movecursorbackward. void EditorBuffer::moveCursorToEnd() { while (cursor->link!= NULL) { movecursorforward();

Two patterns Two linked list patterns for (cp = start; cp->link!= cursor; cp = cp->link) {... code using cp... for (cellt *cp = start; cp!= NULL; cp = cp->link) {... code using cp... Example. display, p. 370.

Deletion void EditorBuffer::deleteCharacter() { if (cursor->link!= NULL) { cellt *oldcell = cursor->link; cursor->link = oldcell->link; delete oldcell; start cursor A B C

Deletion (cont.) void EditorBuffer::deleteCharacter() { if (cursor->link!= NULL) { cellt *oldcell = cursor->link; cursor->link = oldcell->link; delete oldcell; start cursor A B C

Deletion (cont.) void EditorBuffer::deleteCharacter() { if (cursor->link!= NULL) { cellt *oldcell = cursor->link; cursor->link = oldcell->link; delete oldcell; start cursor A C

Insertion void EditorBuffer::insertCharacter(char ch) { cellt *cp = new cellt; cp->ch = ch; cp->link = cursor->link; cursor->link = cp; cursor = cp; start cursor A C cp B

Insertion (cont.) void EditorBuffer::insertCharacter(char ch) { cellt *cp = new cellt; cp->ch = ch; cp->link = cursor->link; cursor->link = cp; cursor = cp; start cursor A C cp B

Insertion (cont.) void EditorBuffer::insertCharacter(char ch) { cellt *cp = new cellt; cp->ch = ch; cp->link = cursor->link; cursor->link = cp; cursor = cp; start cursor A C cp B

Insertion (cont.) void EditorBuffer::insertCharacter(char ch) { cellt *cp = new cellt; cp->ch = ch; cp->link = cursor->link; cursor->link = cp; cursor = cp; start cursor A C cp B

Destructor EditorBuffer:: EditorBuffer() { cellt *cp = start; while (cp!= NULL) { cellt *next = cp->link; delete cp; cp = next; Note. cp points to the cell to be deleted. Save the link field of the current cell in next before deleting the cell.

Relative efficiency Table 10-4, p. 367. Function Array Stack List movecursorforward O(1) O(1) O(1) movecursorbackward O(1) O(1) O(N) movecursortostart O(1) O(N) O(1) movecursortoend O(1) O(N) O(N) insertcharacter O(N) O(1) O(1) deletecharacter O(N) O(1) O(1)

Relative efficiency Table 10-4, p. 367. Function Array Stack List movecursorforward O(1) O(1) O(1) movecursorbackward O(1) O(1) O(N) movecursortostart O(1) O(N) O(1) movecursortoend O(1) O(N) O(N) insertcharacter O(N) O(1) O(1) deletecharacter O(N) O(1) O(1) Question If the cursor pointer pointed to the cell containing the character immediately after the cursor, how would it affect the efficiency?

Doubly linked list To alleviate the problem of going backwards or to the end in linked list, we can used a circular doubly linked list with a dummy cell. start cursor struct cellt { char ch; cellt *prev; cellt *next;

Time-space trade-offs In the doubly linked list implementation, all the operations have O(1) complexity, however, it takes at least nine bytes for each character, about ten times the space in the array implementation.

Time-space trade-offs In the doubly linked list implementation, all the operations have O(1) complexity, however, it takes at least nine bytes for each character, about ten times the space in the array implementation. A hybrid method: A doubly linked list of arrays, where each array represents a line.

Time-space trade-offs In the doubly linked list implementation, all the operations have O(1) complexity, however, it takes at least nine bytes for each character, about ten times the space in the array implementation. A hybrid method: A doubly linked list of arrays, where each array represents a line. A good design demands compromise.