Vectors of Vectors Representing Objects with Two Dimensions.

Slides:



Advertisements
Similar presentations
Parameter Passing Mechanisms Reference Parameters.
Advertisements

File Operations Functions Manipulating Files. Review The fstream library defines two classes: ifstream, for creating connections between programs and.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter 5: Loops and Files.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
1 Lecture 29 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
 Wednesday, 10/16/02, Slide #1 CS106 Introduction to CS1 Wednesday, 10/16/02  QUESTIONS??  Today:  Return and discuss Test #1  Input from and output.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
The switch Statement Selection Revisited. Problem Using OCD, design and implement a program that allows the user to perform an arbitrary temperature conversion.
1 Building Classes (the "++" in C++) (Chapter 14) Representing More Complex Objects.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
1 Chapter 4 Program Input and the Software Design Process.
Matrices Introducing Inheritance. Consider A matrix is a grid in which numbers can be stored. Algorithms for problems in scientific computing frequently.
C ++ Programming Languages Omid Jafarinezhad Lecturer: Omid Jafarinezhad Fall 2013 Lecture 2 Department of Computer Engineering 1.
Controlling Function Behavior Sequence, Selection and Repetition.
File I/O ifstreams and ofstreams Sections 11.1 &
File I/O ifstreams and ofstreams. Some istream Operations istream function Description cin >> ch; Extract next non-whitespace character from cin and store.
DATA STRUCTURES LAB 1 TA: Nouf Al-harbi
C++ Loop Statements Repetition Revisited. Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
1 CS161 Introduction to Computer Science Topic #13.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
Arrays and Vectors Sequential (One-Dimensional) Containers Chapter 12 1.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
Classes Representing Non-Trivial Objects. Problem Write a program that reads a temperature (either Fahrenheit or Celsius), and displays that same temperature.
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.
Class Miscellanea Details About Classes. Review We’ve seen that a class has two sections: class Temperature { public: //... public members private: //...
Practice Building Classes Modeling Objects. Problem Write a program that computes the Dean’s List (full-time students whose GPA 3.0), using a student.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
1 Simple File I/O Chapter 11 Switch Statement Chapter 12.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Loops and Files. 5.1 The Increment and Decrement Operators.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
Introduction to Programming Lecture 40. Class Class is a user defined data type.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Program Input and the Software Design Process ROBERT REAVES.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Std Library of C++ Part 2. vector vector is a collection of objects of a single type vector is a collection of objects of a single type Each object in.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
Class Operations Creating New Types. Review Last time, we began building, a class to allow us to model temperatures: Last time, we began building Temperature,
Objectives You should be able to describe: One-Dimensional Arrays
Problem Session Working in pairs of two, solve the following problem...
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
ifstreams and ofstreams
Vectors of Vectors Representing Objects with Two Dimensions.
Introduction to Programming
Introducing Inheritance
Functions Manipulating Files
Operator Overloading.
Programming with Data Files
Today’s Lecture I/O Streams Tools for File I/O
Chapter 3 Input output.
Vectors of Vectors Representing Objects with Two Dimensions.
Arrays Arrays A few types Structures of related data items
ifstreams and ofstreams
COMS 261 Computer Science I
File I/O in C++ I.
Presentation transcript:

Vectors of Vectors Representing Objects with Two Dimensions

Problem A seating chart is often used by teachers to call on students and simplify attendence tracking: Alan Abrams Beth Bittner Charles Chalmers Debra DeVries Ed Evans Fran Ferguson Gary Grodin Hannah Hollister Ingmar Illich Joe Johnson Louise Lamar Mark Morris Nancy Norris Obadiah O’Hare Pam Parker Write a program that reads a seating chart from a file, displays the chart so that the teacher can call the roll, and writes to a file those who are absent.

Behavior Our program should prompt for and read the name of the data file from the user. It should then open an ifstream to that file. It should then read a seating chart from that file. The program should then prompt for and read the name of an output file, and open an ofstream to that file. The program should display the seating chart, and for each person listed on it, our program should ask the user if that person is present. If the reply is ‘n’, the program should write the name of that person to the output file. The program should then close the fstreams and display a ‘processing complete’ message.

Objects Description Type Kind Name in-file name string varying inFileName input fstream ifstream varying fin seating chart ??? varying seatingChart person string varying ??? out-file name string varying outFileName output fstream ofstream varying fout reply char varying reply

Operations Description Predefined? Library? Name display a string yes string << read a string yes string >> open/close fstreams yes fstream -- read seating chart no print seating chart no read a char yes -- >>

Algorithm 0. Display purpose of program 1. Prompt for and read name of input file into inFileName. 2. Open fin to inFileName, verify open. 3. Fill seatingChart with data from fin. 4. Close fin. 5. Display seatingChart. 6. Prompt for and read name of output file into outFileName. 7. Open fout to outFileName, verify open. 8. For each student in seatingChart: a. Ask if they are present. b. Read reply. c. If reply is ‘n’: write the student to fout. 9. Close fout. 10. Display a ‘processing completed’ message.

Preliminary Analysis Since we are just storing a student’s name, we can use a string to represent student objects. A seating chart has two dimensions -- rows and columns -- so we cannot represent it with a simple vector without losing information. We therefore need to define a class to represent seating chart objects.

Two-Dimensions One way to represent a 2-dimensional structure is to use a vector of vectors: vector > myChart;

Two-Dimensions One way to represent a 2-dimensional structure is to use a vector of vectors: vector > myChart; The “inner” vector represents a row of the chart.

Two-Dimensions One way to represent a 2-dimensional structure is to use a vector of vectors: vector > myChart; The “inner” vector represents a row of the chart. The “outer” vector represents a vector of rows.

Two-Dimensions One way to represent a 2-dimensional structure is to use a vector of vectors: vector > myChart; The “inner” vector represents a row of the chart. The “outer” vector represents a vector of rows. The spaces around the “inner” vector are required -- without them, the compiler may confuse >> with the extraction (input) operator. 

Using typedef Alternatively, we can use the statement to first declare a Row type: Alternatively, we can use the typedef statement to first declare a Row type: typedef vector Row; and then use this new type to declare our chart: vector myChart; The statement has the following pattern: The typedef statement has the following pattern: typedef ExistingType NewType; Its effect is to declare NewType as a synonym or alias for ExistingType. It is commonly used to improve program readability.

Building Classes We can thus start a SeatingChart class as follows: class SeatingChart { public: private: }; The data members myRows and myColumns are not required, but they simplify some operations. int myRows; int myColumns; typedef vector Row; vector myChart;

Prototypes class SeatingChart { public: private: //... data members omitted }; SeatingChart(); SeatingChart(int rows, int columns); int Rows() const; int Columns() const; string Student(int row, int column) const; friend istream & operator>>(istream & in, SeatingChart & chart); friend ostream & operator<<(ostream & in, const SeatingChart & chart);

Operation: Default Constructor The default constructor initializes the data members to default values: SeatingChart aChart; Specification: Postcondition: myRows == 0 && myColumns == 0 && myChart.empty() == true. myChart.empty() == true.

Default Constructor inline SeatingChart::SeatingChart() { myRows = 0; myColumns = 0; } This is simple enough to define inline in the header file: The default vector constructor automatically initializes myChart as an empty vector >.

Explicit-Value Constructor SeatingChart aChart(3, 5); This constructor lets you construct a SeatingChart of a specified size (in rows and columns): Specification: Receive: rows, columns, two int values. Precondition: rows > 0 && columns > 0. Postcondition: myRows == rows && myColumns == columns && myChart is a 2-D vector of rows rows and columns columns. "" [0][1][2][3][4] [2] [1] [0] myChart aChart myRows myColumns 3 5

Explicit-Value Constructor //... #include “SeatingChart.h” SeatingChart:: SeatingChart(int rows, int columns) { assert(rows > 0 && columns > 0); myRows = rows; myColumns = columns; // build: myChart = vector (rows); // “outer” vector for (int i = 0; i < rows; i++) // and myChart[i] = vector (columns); // “inner” vectors } This is sufficiently complicated to define separately:

Explicit-Value Constructor //... #include “SeatingChart.h” SeatingChart:: SeatingChart(int rows, int columns) { assert(rows > 0 && columns > 0); myRows = rows; myColumns = columns; // build: myChart = vector (rows); // “outer” vector for (int i = 0; i < rows; i++) // and myChart[i] = vector (columns); // “inner” vectors } This is sufficiently complicated to define separately: We use one of the three vector constructors to initialize the “outer” vector of myChart.

Explicit-Value Constructor //... #include “SeatingChart.h” SeatingChart:: SeatingChart(int rows, int columns) { assert(rows > 0 && columns > 0); myRows = rows; myColumns = columns; // build: myChart = vector (rows); // “outer” vector for (int i = 0; i < rows; i++) // and myChart[i] = vector (columns); // “inner” vectors } This is sufficiently complicated to define separately: We then use the same vector constructor within a loop to initialize the “inner” vectors of myChart.

Explicit-Value Constructor //... #include “SeatingChart.h” SeatingChart:: SeatingChart(int rows, int columns) { assert(rows > 0 && columns > 0); myRows = rows; myColumns = columns; // build: myChart = vector (rows); // “outer” vector for (int i = 0; i < rows; i++) // and myChart[i] = vector (columns); // “inner” vectors } This is sufficiently complicated to define separately: This initializes each Row of myChart using the default string constructor (which generates empty strings).

Extractors The extractors retrieve data member values: cout << aChart.Rows() << aChart.Columns(); Specifications: Rows:Return myRows. Rows:Return myRows. Columns:Return myColumns. Note that we provide no extractor for myChart, because it contains the actual seating chart.

Default Constructor inline int SeatingChart::Rows() const { return myRows; } These are sufficiently simple to define inline: inline int SeatingChart::Columns() const { return myColumns; }

Element Access The Student() function returns the student assigned to a given seat: cout << aChart.Student(r, c); Specification: Receive: row, column, two int values. Precondition: row is a valid row-index && column is a valid column-index. Return: the string in myChart [row][ column]. Return: the string in myChart [row][ column].

Default Constructor inline string SeatingChart::Student(int row, int column) const { assert(row >= 0 && row < Rows() && column >= 0 && column < Columns()); return myChart[row][column]; } This is probably simple enough to define inline: Note that where a single subscript is used to access an element of a normal vector, two subscripts are needed to access an element of a 2-Dimensional array. The first subscript accesses the correct Row of myChart, the second accesses the correct column in that Row.

Input fin >> aChart; The input operator lets you read a SeatingChart: Specification: Receive: in, an istream; chart, a SeatingChart. Precondition: chart is an empty SeatingChart && in leads to a file containing a seating chart. in leads to a file containing a seating chart. Input: the seating chart, via in. Passback: in, the seating chart read from it; chart, containing the extracted values. chart, containing the extracted values. Return: in, for chaining.

Input Operator //... istream & operator>>(istream & in, SeatingChart & chart) { string firstName, lastName; // each name is a word char separator; // for end-of-line for (;;) // loop1: { // (to fill outer vector) Row aRow; // declare clean Row for (;;) // loop2: { // (to fill inner vector) in >> firstName >> lastName; // read person’s name in.get(separator); // read white-space if (in.eof()) break; // stop at end-of-file aRow.push_back(firstname + ‘ ‘ + lastName); if (separator == ‘\n’) break;// stop at end-of-line } // end loop2 if (in.eof()) break; // stop at end-of-file chart.push_back(aRow); // append Row to chart } // end loop1 return in; // allow chaining } This is sufficiently complicated to define separately.

Output cout << aChart << endl; The output operator lets you write a SeatingChart: Specification: Receive: out, an ostream; chart, a SeatingChart. Output: the values in chart, via out. Passback: out, containing the SeatingChart. Return: out, for chaining.

Output Operator //... ostream & operator<<(ostream & out, const SeatingChart & chart) { for (int r = 0; r < chart.Rows(); r++) { for (int c = 0; c < chart.Columns(); c++) out << chart.Student(r, c) << ‘\t’; out << ‘\n’; } return out; // allow chaining } This is sufficiently complicated to define separately. Such structures are displayed in rows and columns:

Coding Our Algorithm We are now ready to implement our algorithm... // rollCall.cpp //... documentation //... other #includes #include “SeatingChart.h” int main() { cout << “\nTo generate the absentee list,” << “\n enter the input file name“ << “\n containing the seating chart: “; string inFileName; cin >> inFileName;

Coding (Ct’d) //... rollCall.cpp continued ifstream fin(inFileName.data()); assert(fin.is_open()); SeatingChart chart; fin >> chart; fin.close(); cout << “\nEnter the name of the absentee file: “; string outFileName; cin >> outFileName; ofstream fout(outFileName.data()); assert(fout.is_open()); char reply; //...

Coding (Ct’d) //... rollCall.cpp continued for (int r = 0; r < chart.Rows(); r++) for (int c = 0; c < chart.Columns(); c++) { cout << “\nIs “ << chart.Student(r,c) << “ present (y or n)? “; cin >> reply; if (reply == ‘n’) fout << chart.Student << ‘\n’; } fout.close(); cout << “\nProcessing complete. Results are in “ << outFileName << endl; }

Summary Objects consisting of values organized in a 2-D structure (i.e., rows and columns) can be represented by a vector of vectors. Accessing an element of a vector of vectors requires two subscript operations: –one to access the correct element of the “outer” vector (i.e., the correct row); and –one to access the correct element of the “inner” vector (i.e, the correct column within that row). If all elements in a 2-D structure must be processed, use two nested for loops.