Professional Documents
Culture Documents
Lec2 - Template Data Struct
Lec2 - Template Data Struct
Objective:
To introduce Class Templates.
To introduce Function Templates.
To introduce the concepts of Data Structure & Algorithms
Analysis.
To assure that students are able to apply the concepts in the
program.
To assure that students are able to increase their expertise on
the topics.
Templates
Templates are a model of a function or a class that can be
used to generate functions or classes.
Templates provide a major implementation for code
reusability.
From one template, different functions and classes can be
easily created.
All functions created from a function template must have
the same interface that includes the same number of
arguments and return but their argument types and return
value are usually different.
All classes created with a class template have the same
design but their data members and function arguments may
be different.
2
Templates
There are two types of templates:
Function Templates
Class Templates
Overloading
The overloading concept allow the programmer to have
several functions that are doing the same task but
receive or return different types of arguments.
For example, there are two functions that will add two
numbers together.
void Add (int x, int y);
void Add (double a, double b);
This will cost the programmer to have a longer program.
3
Templates
Basic Template Concepts
Generated
Function Generated
Class
Generated
Generated
Function
Class
4
Templates
There are 4 functions that receive different types of data but
doing the same task. What can we do about it?
5
Program Example
Example: Two functions are doing the same task.
//Sum.cpp
#include <iostream>
using namespace std;
//Add 2 integer
void Add(int, int);
//Add 2 double
void Add(double, double);
int main()
{
Add(10, 12); //method call for int
Add(5.5, 3.8); //method call for double
return 0;
}
6
Program Example
Example: Two functions are doing the same task (cont).
//Function implementation
void Add(int x, int y)
{
cout << "Integer: " << x << " + " << y << " = " << x + y << endl;
7
Program Example
Example: Two functions are doing the same task (cont).
Output : Integer : 10 + 12 = 22
Double : 5.5 + 3.8 = 9.3
9
Function Templates
The declaration for standard data types:
int x; double y;
*Note : T and dataType will be the class generic type that can represent
any type of standard data type
10
Program Example
Example: Function Templates.
//Sum.cpp
#include <iostream>
using namespace std;
void Add (T x, T y)
{ cout << x << " + " << y << " = "
<< x + y << endl;
}
int main()
{
Add (10, 12);
Add (5.5, 3.8);
return 0;
}
11
Function Templates
Only one function template needed to allow any method call
with different data types being send to its parameters.
The function will add two numbers and prints out the result
according to the data type.
12
Function Templates
Function Template With More Than One Parameter
A function template can have more than one parameter.
Syntax Declaration:
template <class T1, class T2>
13
Program Example
Example: Function Template with more than one parameter.
//Printing.cpp
#include <iostream>
using namespace std;
template < class T1, class T2 >
15
Function Templates
Function Template With Multiple Type Of Parameters
Besides the generic data type, the parameter in the
function can also be other standard data types such as
integer, float, double, boolean and char.
Syntax Declaration:
template <class T>
void Maximum (T x, int y);
16
Program Example
Example: Function Template with multiple type of parameter.
//PrintArray.cpp
#include <iostream>
using namespace std;
18
Class Templates
Sometimes there is a situation that needed a generic class
being declared.
19
Program Example
Example: Class Template.
//Maximum.h
#ifndef MAXIMUM_H
#define MAXIMUM_H
class Maximum {
private:
T val1, val2;
public:
Maximum(T v1, T v2);
void findMax();
};
#endif
20
Program Example
Example: Class Template (cont).
21
Program Example
Example: Class Template (cont).
//MaxMain.cpp
#include <iostream>
#include "Maximum.h"
using namespace std;
int main()
{
Maximum <int> object1(100, 13);
Maximum <char> object2('a', 'A');
object1.findMax();
cout << "\n";
object2.findMax();
return 0;
}
22
Program Example
Example: Class Template (cont).
23
Intro to Data Structures & Algorithm
24
Algorithm Header
Each algorithm begins with a header that names it, describe
its parameters and lists any pre- and postconditions.
25
Algorithm Header
Example of Algorithm Header:
26
Algorithm Header
Example of Pseudocode:
Algorithm average
Pre nothing
Post average and numbers printed
1 i=0;
2 loop(not end of file)
1 read number into array[i]
2 sum = sum + number
3 i = i + 1;
3 end loop
4 average = sum /i
5 print (average)
end average
27
Abstract Data Type (ADT)
A data type consists of two parts, a set of data and the operations that
can be performed on the data.
Integer type consists of values (whole numbers in some defined range)
and operations (add, subtract, multiply, divide and any other operations
appropriate for the application).
Atomic Data
Atomic data are data that we choose to consider as a single, non
decomposable entity.
For example, the integer 4562 may be considered as a single
integer value. Although it can be decomposed into digits but it will
not have the same characteristics of the original value.
Atomic data type is a set of atomic data with identical properties that
are defined by the set of values and a set of operations that act on
the values.
28
Abstract Data Type (ADT)
Composite Data.
Composite data can be broken out into subfields that have
meaning.
For example, a telephone number can be decomposed into
three parts, the state code (06), the district code(233) and the
phone number(2512).
29
Data Structure
A data structure is an aggregation of atomic and composite
data types into a set with defined relationships.
Structure means a set of rules that hold the data together.
Data structures can be nested. It can consists of other data
structures.
Array Record
Homogeneous sequence of Heterogeneous combination of
data or data types known as data into a single structure with
elements an identified key
Position association among the No association
elements
30
Abstract Data Type (ADT)
An abstract data type is a data declaration packaged
together with the operations that are meaningful for the data
type.
The ADT consists of a set of definitions that allow
programmers to use the functions while hiding the
implementation. This is known as abstraction.
With ADT, users are not concerned with how the task is
done but rather with what it can do. For example, the
concepts of a list. At least three data structures will support
list such as an array, a linked list or a file.
Users should not be aware of the structure used. As long as
they know that they can insert and retrieve data, it should
make no difference on how the data is stored..
31
Abstract Data Type (ADT)
Each ADT class object will have a defined type that the
users must use in their programs.
32
Abstract Data Type (ADT)
A Model for an Abstract Data Type
ADT Class
Application Program
Object
Dynamic Memory
ADT Data
Structure
33
Algorithm Analysis
Algorithm – A set of instructions that must be followed by
the computer to solve problems.
Algorithm Analysis – A technique to analyze an algorithm,
its efficiency and the usage of memory to find the best
algorithm.
An algorithm should have such characteristic:
Solve the problem successfully
An efficient use of memory
Fast run time
The run time usually depends on:
Input size of the program
Code quality
Computer speed
Algorithm complexity 34
Algorithm Analysis
There are two types of algorithm:
Algorithm 1 – The algorithm is easier to understand,
encode and debug.
Algorithm 2 – The algorithm that use the computer
resource like CPU memory and speed with efficient.
Algorithm 1 can be used if the function / method is only used
a few times in the program.
This is to minimize the cost and input size.
Algorithm 2 can be used if the function / method is used a
lot of times and using a bigger input size.
This is because it is important to minimize the cost in
developing the program.
35
Algorithm Analysis
Example of the program:
Example 1:
total = 0;
for (int i=0; i <= n; i++)
total = total + i;
Example 2:
total = n * (n + 1)/2;
Both algorithms are doing the same task but the Example 1
can be understand easily while the Example 2 is much
simpler.
36
Algorithm Analysis
n total (Eg 1) total (eg 2)
Example 1 5 5 1
needs to execute 10 10 1
instruction total 15 15 1
for n times. 20 20 1
Number of
Example 2 Executions
needs to execute
instruction total
only once.
1
n
37
Algorithm Analysis
There are 3 scenario to estimate the efficiency is using
computer resource during run time:
Worst Case Scenario
Best Case Scenario
Average Case Scenario / Theta Notation
38
Algorithm Efficiency
Brassard and Bratley used the term algorithmics which
defines as “The systematic study of the fundamental
techniques used to design and analyze efficient algorithms.”
If a function is linear (contains no loops) then its efficiency is a
function of the number of instructions it contains.
f(n) = efficiency
Linear Loops
1 i=1
2 loop (i<=1000)
1 application code
2 i = i + 1
3 end loop
Assuming i is an integer, the loop is repeated for 1000 times.
f(n) = n
39
Algorithm Efficiency
Linear loops with the number of iterations is half the loop
factor. The higher the factor the lower the number of loops.
1 i=1
2 loop (i<=1000)
1 application code
2 i = i + 2
3 end loop
Assuming i is an integer, the loop is repeated for 500 times.
f(n) = n / 2
40
Algorithm Efficiency
Logarithmic Loops:
Multiply Loops
1 i=1
2 loop (i<1000)
1 application code
2 i = i * 2
3 end loop
Divide Loops
1 i=1
2 loop (i<1000)
1 application code
2 i = i / 2
3 end loop
How many times has the loops repeated?
41
Algorithm Efficiency
Multiply Divide
Loop Value of i Loop Value of i
1 1 1 1000
2 2 2 500
3 4 3 250
4 8 4 125
5 16 5 62
6 32 6 31
7 64 7 15
8 128 8 7
9 256 9 3
10 512 10 1
(exit) 1024 (exit) 0
42
Algorithm Efficiency
The number of iterations is 10 in both cases.
The reason is that in each iteration the value of i doubles for
the multiply loop and is cut in half for the divide loop.
The number of iterations is a function of the multiplier or
divisor, in this case is 2.
The loop continues while the condition shown below is true.
Multiply: 2ⁿ< 1000
Divide: 1000 / 2ⁿ>= 1
n = iterations
Iterations in loops that multiply or divide are determined by
the following formula.
f(n) = [log₂ n]
43
Summary
LINEAR LOOPS
For + and – operations the f(n) is equivalent to n.
If i (+ or – ) any constant number the efficiency is n/
(constant number)
LOGARITHMIC LOOPS
For * and / operations the f(n) is log [constant number] n
44
Algorithm Efficiency
Nested Loops must be determined on how many iterations
each loops completes.
The total is then the product of the number of iterations in
the inner loop and the number of iterations in the outer loop.
The loop continues while the condition shown below is true.
Iterations = outer loop iterations x
inner loop iterations
45
Algorithm Efficiency
Linear Logarithmic
1 i=1
2 loop (i<=10)
1 j=1
2 loop(j<=10)
1 application code
2 j = j * 2
3 end loop
4 i = i + 1
3 end loop
46
Algorithm Efficiency
However, because the inner loop is controlled by an outer
loop, the above formula must be multiplied by the number of
times the outer loop executes which is 10.
10 x [log₂ 10]
Which is generalized as
f(n) = [nlog₂ n]
47
Algorithm Efficiency
Dependent Quadratic
1 i=1
2 loop (i<=10)
1 j=1
2 loop(j<=i)
1 application code
2 j = j + 1
3 end loop
4 i = i + 1
3 end loop
48
Algorithm Efficiency
The outer loop is the same as the previous loop. However
the inner loop depends on the outer loop for one of its
factors. The number of iterations in the body of the inner
loop is calculate asshown below
1 + 2 + 3 + . . . + 9 + 10 = 55
49
Algorithm Efficiency
Quadratic
1 i=1
2 loop (i<=10)
1 j=1
2 loop(j<=10)
1 application code
2 j = j + 1
3 end loop
4 i = i + 1
3 end loop
50
Algorithm Efficiency
Each loop executes the same number of times.
The outer loop is executed ten times. For each of its
iterations, the inner loop is also executed ten times.
10 x 10 = 100
51
The End
Q&A
52