730 likes | 1.16k Views
CH2. ARRAYS . 2.1 Abstract Data Types and the C++ Class. 2.1.1 C++ Class : represents an ADT Consists of four components class name data members member functions levels of program access public : anywhere private : within its (friend) class a function
E N D
2.1 Abstract Data Types and the C++ Class 2.1.1 C++ Class : represents an ADT • Consists of four components • class name • data members • member functions • levels of program access • public : anywhere • private : within its (friend) class a function • protected : within its class friend
2.1 Abstract Data Types and the C++ Class(Cont’) #ifndef RECTANGLE_H #define RECTANGLE_H // In the header file Rectangle.h class Rectangle { public: // the following members are public // The next four members are member functions Rectangle(); // constructor ~Rectangle(); // destructor int GetHeight(); // returns the height of the rectangle int GetWidth(); // returns the width of the rectangle private: // the following members are private // the following members are data members int x1, y1, h, w; // (x1, y1) are the coordinates of the bottom left corner of the rectangle // w is the width of the rectangle; h is the height of the rectangle }; #endif Program 2.1 : Definition of the C++ class Rectangle
2.1 Abstract Data Types and the C++ Class(Cont’) 2.1.2 Data Abstraction and Encapsulation in C++ • Data encapsulation of C++ class • all data members are private (or protected) • external access to data members are by member functions • Separation of specification and implementation of member functions • specification (function prototype) • name of functions • type of function arguments • type of function result • Implementation • placed in a source file of the same name • can be included inside its class definition
2.1 Abstract Data Types and the C++ Class(Cont’) // In the source file Rectangle.C #include "Rectangle.h" // The prefix “Rectangle::" identifies GetHeight() and // GetWidth() as member functions // belonging to class Rectangle. It is required because the member functions // are implemented outside their class definition int Rectangle::GetHeight() {return h;} int Rectangle::GetWidth() {return w;} Program 2.2 : Implementation of operations on Rectangle
2.1 Abstract Data Types and the C++ Class(Cont’) 2.1.3 Declaring class objects • in the same way as variables • Invoking member functions • using component selection operators • dot(.) : direct selection • arrow : indirect selection through a pointer
2.1 Abstract Data Types and the C++ Class(Cont’) // In a source file main.C #include <iostream.h> #include "Rectangle.h" main() { Rectangle r, s; // r and s are objects of class Rectangle Rectangle *t = &s; // t is a pointer to class object s ….. // use . to access members of class objects. // use → to access members of class objects through pointers. if (r.GetHeight()*r.GetWidth() >t→GetHeight() * t→GetWidth()) cout << " r "; else cout << " s "; cout << "has the greater area" << endl; } Program 2.3 : A C++ code fragment demonstrating how Rectangle objects are declared and member functions invoked
2.1 Abstract Data Types and the C++ Class(Cont’) 2.1.4 Special Class Operations • Constructor • a member function which initializes data members of an object • If provided for a class, automatically executed when an object of that class is created • must be public • the name must be identical to the name of the class • must not specify a return type or return a value Rectangle::Rectangle(int x, int y, int height, int width) { x1=x; y1=y; h=height; w=width; } Program 2.4 : Definition of a constructor for Rectangle
2.1 Abstract Data Types and the C++ Class(Cont’) • initialize Rectangle object using constructor • Rectangle r(1, 3, 6, 6); • Rectangle *s = new Rectangle(0, 0, 3, 4); • initialize using a default constructor • Rectangle r; Rectangle::Rectangle (int x=0, int y=0, int height=0, int width=0) : x1 (x), y1(y), h(height), w(width) { } Program 2.5 : A default constructor
2.1 Abstract Data Types and the C++ Class(Cont’) • Destructor • a member function which deletes data members • automatically invoked when a class object goes out of scope or is deleted • must be public • its class name prefixed with ~ • if a data member is a pointer, only the space of the pointer is returned • Operator overloading • polymorphism : same operator for different situations • for example, algorithm comparing two floats is different from algorithm comparing two ints
2.1 Abstract Data Types and the C++ Class(Cont’) int Rectangle::operator==(const Rectangle &s ) { if (this == &s) return 1; if ((x1 == s.x1) && (y1 == s.y1) && (h == s.h) && (w == s.w)) return 1; else return 0; } Program 2.6 : Overloading operator == for class Rectangle
2.1 Abstract Data Types and the C++ Class(Cont’) • this • represents a pointer to the object that invoked a member function • *this represents the object
2.1 Abstract Data Types and the C++ Class(Cont’) Ostream& operator<<(ostream& os, Rectangle& r) { os << “Position is : ” << r.xl << “ ”; os << r.yl << endl; os << “Height is : ” << r.h << endl; os << “Width is : ” << r.w << endl; return os; } Program 2.7 : Overloading operator << for class Rectangle
2.1 Abstract Data Types and the C++ Class(Cont’) 2.1.5 Miscellaneous Topics • static class data member • a global variable for its class • there is only one copy of a static data member and all class objects share it • declaration does not constitute a definition
2.1 Abstract Data Types and the C++ Class(Cont’) 2.1.6 ADTs and C++ classes • They are similar • Some operators in C++, when overloaded for user defined ADTs, are declared outside the C++ class definition of the ADT
2.1 Abstract Data Types and the C++ Class(Cont’) class NaturalNumber{ // An ordered subrange of the integers starting at zero and ending at // the maximum integer (MAXINT) on the computer public: NaturalNumber Zero(); // returns 0 Boolean IsZero(); // if *this is 0, return TRUE; otherwise, return FALSE NaturalNumber Add(NaturalNumber y); // return the smaller of *this+y and MAXINT; Boolean Equal(NaturalNumber y); // return TRUE if *this==y; otherwise return FALSE NaturalNumber Successor(); // if *this is MAXINT return MAXINT; otherwise return *this+1 NaturalNumber Substract(NaturalNumber y); // if *this<y, return 0; otherwise return *this-y }; ADT 1.2 : Abstract data type NaturalNumber
2.2 Array As Abstract Data Type • Array • a set of pairs <index, value> • ADT for array provides operations • retrieves a value • stores a value • C++ Array • index starts at 0 • C++ does not check bounds for an array index • example • float example[n]; • ith element: example[i] and *(example+i)
2.2 Array As Abstract Data Type(Cont’) Class GeneralArray { // objects: A set of pairs <index, value> where for each value of index // in IndexSet there is a value of type float. // IndexSet is a finite ordered set of one or more dimensions, // for example, {0, ..., n-1} for one dimension, // {(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)} for two // dimensions, etc. public: GeneralArray(int j, RangeList list, float initValue = defaultValue); // The constructor GeneralArray creates a j dimensional array // of floats; the range of the kth dimension is given by the // kth element of list. For each index i in the index set, insert // <i, initValue> into the array.
2.2 Array As Abstract Data Type(Cont’) float Retrieve(index i); // if (i is in the index set of the array) return the float // associated with i in the array; else signal an error. void Store(index i, float x); // if (i is in the index set of the array) delete any pair of the // form <i, y> present in the array and insert the new pair // <i, x>; else signal an error. }; // end of GeneralArray ADT 2.1 : Abstract data type GeneralArray
2.3 Polynomial Abstract Data Type • Ordered (or linear) list • days of the week : (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday) • years Switzerland fought in WWII : () • Operations on lists (a0, a1, ..., an-1) : • find the length, n, of the list • read the list from left to right (or reverse) • retrieve the ith element, 0≤i<n • store a new value into the ith position, 0≤i<n • insert a new element at the position i, 0≤i<n • delete the element at position i, 0≤i<n
2.3 Polynomial Abstract Data Type(Cont’) • Polynomial • requires ordered lists • the largest exponent is called degree • sum and product of polynomials A(x) = ∑aixi and B(x) = ∑bixi • A(x) + B(x) = ∑(ai + bi)xi • A(x) ‧ B(x) = ∑(aixi ․∑(bjxj))
2.3 Polynomial Abstract Data Type(Cont’) Class Polynomial { // objects : p(x) = a0xe0 + … + anxe0 ; a set of ordered pairs of <ei, ai>, // where ai ∈ Coefficient and ei∈Exponent // We assume that Exponent consists of integers ≥ 0 public: Polynomial(); // return the polynomial p(x)=0 int operator!(); // If *this is the zero polynomial, return 1; else return 0; Coefficient Coef(Exponent e); // return the coefficient of e in *this Exponent LeadExp(); // return the largest exponent in *this
2.3 Polynomial Abstract Data Type(Cont’) Polynomial Add(Polynomial poly); // return the sum of the polynomials *this and poly Polynomial Mult(Polynomial poly); // return the product of the polynomials *this and poly float Eval(float f); // Evaluate the polynomial *this at f and return the result. }; // end of polynomial ADT 2.2 : Abstract data type Polynomial
2.3 Polynomial Abstract Data Type(Cont’) 2.3.1 Polynomial Representation • Principle • unique exponents are arranged in decreasing order
2.3 Polynomial Abstract Data Type(Cont’) • Representation 1 (Array: static memory allocation) • define the private data members of Polynomial private : int degree ; // degree≤MaxDegree float coef[MaxDegree+1] ; • for Polynomial object a, n≤MaxDegree a.degree=n a.coef[i]=an-i, 0≤i≤n • a.coef[i] is the coefficient of xn-I A(x)=anxn+an-1xn-i+...+a1x+a0 • leads to a very simple algorithms for many of the operations on polynomials • wastes computer memory • for example, if a.degree MaxDegree
2.3 Polynomial Abstract Data Type(Cont’) • Representation 2 (Array: dynamic memory allocation) • define coef with size a.degree+1 • declare private data members private : int degree ; float *coef ; • add a constructor to Polynomial Polynomial::Polynomial(int d) { degree=d ; coef=newfloat[degree+1] ; } • wastes space for sparse polynomials • for example, x1000+1
2.3 Polynomial Abstract Data Type(Cont’) • Representation 3 • previously, exponents are represented by array indices • now, (non-zero) exponents are stored • all Polynomials will be represented in a single array called termArray • termArray is shared by all Polynomial objects • it is declared as static • each element in termArray is of type term class term { friend Polynomial ; private : float coef ; // coefficient int exp ; // exponent };
2.3 Polynomial Abstract Data Type(Cont’) • declare private data members of Polynomial • class Polynomial { private : static term termArray[MaxTerms]; static int free; int Start, Finish; public: Polynomial ADD(Polynomial poly); ... } • required definitions of the static class members outside the class definition term Polynomial::termArray[MaxTerms]; int Polynomial::free=0; // next free location in termArray • A(x)=2x1000+1, B(x)=x4+10x3+3x2+1
2.3 Polynomial Abstract Data Type(Cont’) A.Start A.Finish B.Start B.Finish Free coef 2 1 1 10 3 1 exp 1000 0 4 3 2 0 0 1 2 3 4 5 6 Figure 2.1 : Array representation of two polynomials
2.3 Polynomial Abstract Data Type(Cont’) • A(x) has n nonzero terms • A.Finish=A.Start+n-1 • if n=0, A.Finish=A.Start-1 • comparison with Representation 2 • Representation 3 is superior when many zero terms are present as in A(x) • when all terms are nonzero, as in B(x), Representation 3 uses about twice as much space as Representation 2
2.3 Polynomial Abstract Data Type(Cont’) 2.3.2 Polynomial Addition • Representation 3 is used • C(x)=A(x)+B(x)
2.3 Polynomial Abstract Data Type(Cont’) Polynomial Polynomial::Add(Polynomial B) // return the sum of A(x) (in *this) and B(x) { Polynomial C; int a = Start; int b = B.Start; C.Start = free; float c; while ((a<=Finish) && (b<=B.Finish) switch (compare(termArray[a].exp, termArray[b].exp)){ case '=': c = termArray[a].coef + termArray[b].coef; if (c) NewTerm(c, termArray[a].exp); a++; b++; break; case '<': NewTerm(termArray[b].coef, termArray[b].exp); b++; break;
2.3 Polynomial Abstract Data Type(Cont’) case '>': NewTerm(termArray[a].coef, termArray[a].exp); a++; }// end of switch and while // add in remaining terms of A(x) for (; a<=Finish; a++) NewTerm(termArray[a].coef, termArray[a].exp); // add in remaining terms of B(x) for (; b<=B.Finish; b++) Newterm(termArray[b].coef, termArray[b].exp); C.Finish = free - 1; return C; }// end of Add Program 2.8 : Adding two polynomials
2.3 Polynomial Abstract Data Type(Cont’) void Polynomial::NewTerm(float c, int e) // Add a new term to C(x). { if (free>=MaxTerms) { cerr << "Too many terms in polynomials" << endl; exit(1); } termArray[free].coef = c; termArray[free].exp = e; free++; }// end of NewTerm Program 2.9 : Adding a new term
2.3 Polynomial Abstract Data Type(Cont’) • Analysis of Add • m and n are number of nonzero-terms in A and B, respectively • the while loop of line 5 is bounded by m+n-1 • the for loops of lines 21 and 24 are bounded by O(n+m) • summing up, the asymptotic computing time is O(n+m) • Disadvantages of representing polynomials by arrays • space must be reused for unused polynomials • linked lists in chapter 4 provide a solution
2.4 Sparse Matrices 2.4.1 Introduction • Matrix with m rows and n columns • m×n (m by n) • mn elements • when m=n, the matrix is square • Storing a matrix • two dimensional array A[m][n] • an element is A[i][j] • sparse matrix • store only the nonzero elements
1 1 2 3 4 5 0 1 2 0 15 0 0 12 0 -15 0 -27 3 4 1 0 11 3 0 0 0 1 6 82 -2 2 0 0 0 -6 0 0 2 109 -64 11 3 0 0 0 0 0 0 3 12 8 9 4 91 0 0 0 0 0 4 48 27 47 5 0 0 28 0 0 0 2.4 Sparse Matrices(Cont’) • Matrix operations • Creation • Transposition • Addition • multiplication (a) (b) Figure 2.2 : Two matrices
2.4 Sparse Matrices(Cont’) Class SparseMatrix { // objects : A set of triples, <row, column, value>, where row // and column are integers and form a unique combination; value // is also an integer. public: SparseMatrix(int MaxRow, int MaxCol); // the constructor function creates a SparseMatrix // that can hold up to MaxItems=MaxRow x MaxCol and whose // maximum row size is MaxRow and whose maximum // column size is MaxCol SparseMatrix Transpose(); // returns the SparseMatrix obtained by interchanging the // row and column value of every triple in *this
2.4 Sparse Matrices(Cont’) SparseMatrix Add(SparseMatrix b); // if the dimensions of a(*this) and b are the same, then // the matrix produced by adding corresponding items, // namely those with identical row and column values is // returned else error. SparseMatrix Multiply(SparseMatrix b); // if number of columns in a (*this) equals number of // rows in b then the matrix d produced by multiplying a // by b according to the formula // d[i][j]= (a[i][k]·b[k][j]), // where d[i][j] is the (i, j)th element, is returned. // k ranges from 0 to the number of columns in a-1 // else error. }; ADT 2.3 : Abstract data type SparseMatrix
2.4 Sparse Matrices(Cont’) 2.4.2 Sparse Matrix Representation • Representation • use the triple <row, col, value> to represent an element • store the triples by rows • for each row, the column indices are in ascending order • store the number of rows, columns, and nonzero elements
2.4 Sparse Matrices(Cont’) • C++ code class SparseMatrix; // forward declaration class MatrixTerm { friend class SparseMatrix private: int row, col, value; }; class SparseMatrix { private: int Rows, Cols, Terms; MatrixTerm smArray[MaxTerms]; public: SparseMatrix Transpose(); ... }
2.4 Sparse Matrices(Cont’) • Representation of the matrix of Figure 2.2(b) using smArray row col value row col value smArray[0] 0 0 15 smArray[0] 0 0 15 [1] 0 3 22 [1] 0 4 91 [2] 0 5 -15 [2] 1 1 11 [3] 1 1 11 [3] 2 1 3 [4] 1 2 3 [4] 2 5 28 [5] 2 3 -6 [5] 3 0 22 [6] 4 0 91 [6] 3 2 -6 [7] 5 2 28 [7] 5 0 -15 • (b) Figure 2.3 : Sparse matrix and its transpose stored as triples
2.4 Sparse Matrices(Cont’) 2.4.3 Transposing a Matrix • n element at [i][j] will be at [j][i] for (each row i) take element (i, j, value) and store it in (j, i, value) of the transpose; • Example • (0, 0, 15) → (0, 0, 15) • (0, 3, 22) → (3, 0, 22) • (0, 5, -15) → (5, 0, -15) • (1, 1, 11) → (1, 1, 11) • need to insert many new triples, elements are moved down very often • Find the elements in the order for (all elements in column j) place element (i, j, value) in position (j, i, value);
2.4 Sparse Matrices(Cont’) SparseMatrix SparseMatrix::Transpose() // return the transpose of a (*this) { SparseMatrix b; b.Rows = Cols; // rows in b = columns in a b.Cols = Rows; // columns in b = rows in a b.Terms = Terms; // terms in b = terms in a if (Terms > 0) // nonzero matrix { int CurrentB = 0; for (int c = 0; c < Cols; c++) // transpose by columns for (int i = 0; i < Terms; i++) // find elements in column c
2.4 Sparse Matrices(Cont’) if (smArray[i].col ==c) { b.smArray[CurrentB].row = c; b.smArray[CurrentB].col = smArray[i].row; b.smArray[CurrentB].value = smArray[i].value; CurrentB++; } } // end of if (Terms > 0) return b; } // end of transpose Program 2.10 : Transposing a matrix
2.4 Sparse Matrices(Cont’) • Analysis of transpose • the number of iterations of the for loop at line 12 is terms • the number of iterations of the for loop at line 11 is columns • total time is O(terms·columns) • total space is O(space for a and b) • Using two-dimensional arrays for(int j=0; j<columns; j++) for(int i=0; i<rows; i++) B[j][i]=A[i][j]; • total time is O(rows·columns)
2.4 Sparse Matrices(Cont’) • Comparison • O(terms·columns) =O(rows·columns2) > O(rows·columns) • space-time trade-off
2.4 Sparse Matrices(Cont’) • FastTranspose algorithm • determine the number of elements in each column of a → the number of elements in each row of b → starting point of each of b's rows • move elements of a one by one into their correct position in b • values for Figure 2.3 (b) matrix [0] [1] [2] [3] [4] [5] RowSize = 2 1 2 2 0 1 RowStart = 0 2 3 5 7 7
2.4 Sparse Matrices(Cont’) • asymptotic complexity • there are four loops O(columns+terms) • if terms → rows·columns, O(rows·columns) • if terms << rows·columns, less than O(rows·columns) • requires space for RowSize and RowStart
2.4 Sparse Matrices(Cont’) SparseMatrix SparseMatrix::FastTranspose() // The transpose of a (*this) is placed in b and is found in // O(terms+columns) time. { int *RowSize = new int[Cols]; int *RowStart = new int[Cols]; SparseMatrix b; b.Rows = Cols; b.Cols = Rows; b.Terms = Terms; if (Terms>0) // nonzero matrix { // compute RowSize[i] = number of terms in row i of b for (int i = 0; i<Cols; i++) RowSize[i] = 0; // initialize for (i = 0; i<Terms; i++) RowSize[smArray[i].col]++; // RowStart[i] = starting position of row i in b RowStart[0] = 0;