Professional Documents
Culture Documents
Lecture 2-2022
Lecture 2-2022
Chapter 2 Arrays
• Data Encapsulation
– Declaring all data members of a class to be private (or
protected)
– External access→ define member functions that get and
set data members
• Data Abstraction
– Specification
• of operations of a class is separated from their implementation,
e.g., Rectangle.h →Rectangle.cpp
• Specification is contained in the public portion of a class
– Abstraction data type is implementation-independent
• Constructor
– Is a member function which initializes data members of an object
– If provided, it is automatically executed when an object of that class
is created
– If not provided, data members are not properly initialized
• Destructor
– Is a member function which deletes data members immediately
before the object disappears
– Invoked automatically when a class object goes out of scope or
explicitly deleted
– Pointer data member → the object that it was pointing to is not
deleted
Memory
allocation Rectangle r, s;
Rectangle *t = &s;
t: 0xaaaa 0xdddd
Pointer
to object
s: 0xdddd Rectangle
• Overload operators
– for user-defined data types is allowed in C++.
– Takes the form of a class member function or an
ordinary function
1. int Rectangle:: operator==(const Rectangle &s) Program 2.6
2. {
3. if(this==&s) return (1); //check if two objects are the same
4. if( (xLow=s.x1) &&(yLow==s.y1) &&(h==s.h) (w==s.w) {
5. return (1);
6. else return (0)
7. } “this” is the pointer to the
data object upon which the
operators is performed
J.-J. Chen, EE NTUST 2 Array-11
Operator Overloading ==
#include "iostream.h"
class complex {
public:
complex(int re, int im) { real=re; imaginary=im;}
int get_real() {return(real);}
int get_imaginary() {return(imaginary);}
int operator==(complex x) {
if(real==x.get_real() && imaginary==x.get_imaginary())
return (1);
else return(0);
}
private: 1. main(){
int real; 2. int i;
int imaginary; 3. complex a(1, 2),b(3, 4);
} 4. cout << (a==b);
5. }
• Struct
– Is idential to a class, except that the default level of access is public
– In a class, the default is private class
• Union
– A struct that reserves storage for the largest of its data members
– Useful for applications where only one of many possible data item
needs to be stored at any time
• Static class data member
– A global variable for its class class X {
public:
– A definition of the data member int normalValue = 5;
outside the class definition is required static const int i = 0;
// declaration, with initializer
};
const int X::i; // definition
struct exclusive_pair{
union {
int n1; // 32 bits A exclusive_pair contains only
an integer or a floating point
float n2; // 32 bits
number
} → requires only 32 bits
}
main()
{
Results: 10 10
ex_pair p;
p.n1=1; p.n2=10;
cout << p.n1 << “ “<<p.n2;
}
J.-J. Chen, EE NTUST 2 Array-18
OUTLINE
• C++ Class
• The Array as an Abstract Data Type
• The Polynomial
• Sparse Matrix
• The String
• Traditional Array
– Is viewed as a consecutive set of memory locations
– Is a set of ordered pair, i.e., <index,value>
– Provides two standard operations
• Store a value to a given index
• Retrieve a value corresponding to a given index
– Store and retrieve are performed in a constant time
• More robust array
– To avoid out-of-bound access
• A n-dimensional array
– Is usually implemented as a one-dimensional array
– A mapping mechanism is needed
– Assumption of A[u1][u2]…[un]
• First index range: [p1…q1]
• Second index range:[p2…q2]
• ….
• N-th index range:[pn…qn]
– The total number of elements in this n-dimensional
array is
(q − p +1)
n
i =1 i i
Row 0
X X X X
Row 1 X X X X
Row u1 - 1
X X X X
u2 u2
elements elements
• Formula
– Assume p is the address of A[0][0][0]
– Address for A[i][0][0] = p + i u2u3
– Address for A[i][j][0] = p + (i u2u3)+ j u3
– Address for A[i][j][k] = p + (i u2u3)+( j u3 ) + k
A[i1][i2]…[in] p + ija j
(Row major order)
mapped to j =1
where a j = k = j +1 uk , 1 j n
n
an = 1
u2
u1
u3
(a) 把三維陣列A[u1][u2][u3]視為u1個二維陣列
i u 2 u 3 個元素
(b) 一個三維陣列的循序列主序表示法。每一個二維陣列都用圖2.6的方法來表示。
圖2.7:a[u1][u2][u3]的循序表示法
J.-J. Chen, EE NTUST 2 Array-26
OUTLINE
• C++ Class
• The Array as an Abstract Data Type
• The Polynomial
• Sparse Matrix
• The String
Polynomial();
// return the polynomial p(x)=0
• Example
– Assume that a is a polynomial class object & n < = MaxDegree
– E.g., an xn ++ a1x1 + a0
– Then, a.degree = n and
a.coef [i ] = an −i ,
0in
• Disadvantage
– Wasteful in its use of computer memory
• Constructor Polynomial::Polynomial(int d)
{
degree = d;
coef = new float [degree+1]
}
• Advantage
– The size of array can be dynamically determined,
leading to a more efficient memory usage
• Sparse polynomial
– E.g., x + 1 → <coef, exp> list →
100
{<1,100>,<1,0>}
• Shared single array is used
– All polynomials, if many in the program, will be put
together as a shared single array
// private data members of Polynomial
class Polynomial; private:
static Term termArray[MaxTerms];
class Term { static int free;
friend Polynomial; int Start, Finish;
private:
float coef ; // coefficient // static data outside class declaration
int exp; // exponent Term Polynomial::termArray[MaxTerms];
} int Polynomial::free=0;
// next free location in termArray
J.-J. Chen, EE NTUST 2 Array-31
Examples: Array for Two Polynomials
• A(x)=2x100+1
– A.Start = 0; A.Finish = 1
• B(x)=x4+10x3+3x2+1
– B.Start=2; B.Finish=5
coef 2 1 1 10 3 1
exp 100 0 4 3 2 0
index 0 1 2 3 4 5 6
A zero polynomial Z(x)=0→ Z.Finish=Z.Start - 1
J.-J. Chen, EE NTUST 2 Array-32
Polynomial Addition
1. Polynomial Polynomial::Add(Polynomial B) Program 2.8
2. //return the sum of A(x)(in *this) and B(x)
3. {
4. Polynomial C; int a=Start; int b=B.Start; C.Start=free; float c;
5. while ((a<=Finish) && (b<=B.Finish))
6. switch (compares(termArray[a].exp,termArray[b].exp)){
7. case '=':
8. c=termArray[a].coef + termArray[b].coef;
9. if(c) NewTerm(c,termArray[a].exp);
10. a++;b++;
11. break;
12. case '<';
13. NewTerm(termArray[b].coef, termArray[b].exp);
14. b++;
15. break;
16. case '>';
17. NewTerm(termArray[a].coef,termArray[a].exp);
18. a++;
19. } //end of switch & while
J.-J. Chen, EE NTUST 2 Array-33
Polynomial Addition
Program 2.8
1 Polynomial Polynomial::Add(Polynomial b)
2 { // 回傳多項式 *this與b的和
3 Polynomial c;
4 int aPos = 0, bPos = 0;
5 while ((aPos < terms) && (bPos < b.terms))
6 if (termArray [aPos].exp = = b.termArray [bPos].exp) {
7 float t = termArray [aPos].coef + b.termArray [bPos].coef;
8 If (t) c.NewTerm (t, termArray [aPos].exp);
9 aPos++; bPos++;
10 }
11 else if (termArray [aPos].exp < b.termArray [bPos].exp) {
12 c.NewTerm (b.termArray [bPos].coef, b.termArray [bPos].exp);
13 bPos++;
14 }
15 else {
16 c.NewTerm (termArray [aPos].coef,termArray [aPos].exp);
17 aPos++;
18 }
19
19 // 把 *this中剩下的項給加進來
20 for ( ; aPos < terms ; aPos++)
21 c.NewTerm (termArray [aPos].coef, termArray [aPos].exp);
22 // 把 b(x) 中剩下的項給加進來
23 for ( ; bPos < b.terms ; bPos++)
24 c.NewTerm (b.termArray [bPos].coef, b.termArray [bPos].exp);
25 return c;
26 }
• C++ Class
• The Array as an Abstract Data Type
• The Polynomial
• Sparse Matrix
• The String
Sparse Matrix
Is a matrix in which most elements are zero
15 0 0 22 0 − 15
− 27 3 4 0 11 3 0 0 0
6 82 − 2
0 0 0 −6 0 0
109 − 64 11
0 0 0 0 0 0
12 8 9 91 0 0 0 0 0
48 27 47
0 0 28 0 0 0
• Memory Space
– Use two-dimensional array for sparse matrix is a big
waste of memory space
• Representation
– Use triple <row, column, value>
– Store triples row by row
– For all triples within a row, their column indices are in ascending
order.
– Must know the number of rows and columns and the number of
nonzero elements
15 0 0 22 0 − 15
0 11 3 0 0 0
0 0 0 −6 0 0
0 0 0 0 0 0
91 0 0 0 0 0
0 0 28 0 0 0
14
• Step 1:
– Scan Matrix A to construct the RowSize array of AT
1 0 2 3 1 0 0 0
0 0 1 2 0 0 0 4
A=
Matrix A RowSize array of AT A =
T
0 0 1 0 2 1 1 0
0 4 0 0 3 2 0 0
(row,col,value) 0 1 2 3
0 0 1 → 1 0 0 0
Row0 0 2 2 → 1 0 1 0
0 3 3 → 1 0 1 1
Row1 1 2 1 → 1 0 2 1
1 3 2 → 1 0 2 2
Row2 2 2 1 → 1 0 3 2
Row3 3 1 4 → 1 1 3 2
1 3 2 2 2 1 4 6
1 1 4 7
Row2 2 2 1 3 0 3 5 3
1 1 5 7
Row3 3 1 4 3 1 2 6 5
1 2 5 7
index Fill-in order
J.-J. Chen, EE NTUST 2 Array-51
Principles in Fast Transpose
Row1
0 3 3
1 2 1
1 0 2 3 0
0 =2
1 3 4
2 0 2 B.col2
1 3 2 1 2 1 1
Row2 2 2 1
0 3 1 2 B.col3
Row3 3 1 4
• Notation
Ann Bnn
– Ai: the number of non-zero elements in i-th row of A
– Bj: the number of non-zero elements in j-th col. of B (j-th row of BT)
• C++ Class
• The Array as an Abstract Data Type
• The Polynomial
• Sparse Matrix
• The String
H e l l o W o r l d \0
• Problem
– Finding if a pattern is contained in another string
• Example
– Pattern: “data structure”
– String: “The course identifier of data structure is EE34..”
– Result = 26
– If pattern does not exist in the string, return -1
• A match
• Return the starting index of the sliding window = 47
▪Time Complexity
−the worst-case complexity of this algorithm = O (mn)
where m is the length of the pattern
n is the length of the string
▪The window matching is performed for n times and each of them
may take m steps to complete in the worst case
• Definition
– If p = p0p1….pn-1 is a pattern, then its failure function, f,
is defined as: f(j)=
(1) largest k<j such that p0p1….pk = pj-kpj-k+1….pj
if such a k0 exist
(2) otherwise f(j)= -1;
• Example
a b c a b c a c a b
Target Pattern a b c a b c a c a b
j 0 1 2 3 4 5 6 7 8 9
F(j) -1 -1 -1 0 1 2 3 -1 0 1
• Usage
– It decides the leap size after a partial match
• Rule of pattern matching
– If a partial match is found such that
( si-j…si-1 ) = ( p0p1…pj-1) and si pj,
then matching may be resumed by comparing:
(1) si and pf(j-1)+1 if j0
(2) si+1 and p0 if j=0;
si si does not go backward after a partial mismatch
String: data encapsulation is an important concept in data structure
Pattern: data structure (14 characters)
pj
f(5)=-1 → next character in pattern to be checked
2 Array-67
is p0 &
J.-J.sChen, EE NTUST
i
Example of
using Failure Function
s5
String a b c a b c a b y a c a b
Target pattern a b c a b y a c a b
New p
+1 p5
j 0 1 2 3 4 5 6 7 8 9
f(j) -1 -1 -1 0 1 -1 0 -1 0 1
S3
s5
String a b c a b c a b y a c a b
Target pattern a b c a b y a c a b
p2
j 0 1 2 3 4 5 6 7 8 9
f(j) -1 -1 -1 0 1 -1 0 -1 0 1
…→
• Rule f(j)=
−1 if j = 0
m
f ( j − 1) + 1 where m is the least integer k for which p f k (j-1 )+1 = p j
−1 if there is no k satisfying the above
j 0 1 2 3 4 5 6 7 8 9 10 11
f(j) -1 -1 -1 0 1 0 1 2 3 4 2 -1
12. } −1 if there is no k satisfying the above
j 0 1 2 3 4 5 6 7 8 9 10 11
f(j) -1 -1 -1 0 1 0 1 2 3 4 2 -1
Horner’s method:
P(x) = (((4*x + 7) * x – 2) * x + 3) * x + 6