-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.cpp
More file actions
60 lines (48 loc) · 1.01 KB
/
template.cpp
File metadata and controls
60 lines (48 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// Example of how to use template
//
// Week 2, lecture 2.1
//
#include<iostream>
using namespace std;
#include <vector>
//-=-=-=-=-=-=-=-=-=-=-
//
// Ideas
// -----
// data is not mutable, usa a const
// s with default 0
//
// I can call this function with:
//
// sum(scores, 92)
// sum(scores, 92,58) -> In this case s starts with 58
//
// You could use a default falue for size variable
//
//-=-=-=-=-=-=-=-=-=-=-
template <class T>
T sum(T data[], int size, T s = 0) {
for (int i = 0; i < size; ++i)
s+= data[i]; // += must work for T
return s;
}
template <class T>
T display(T data[], int size) {
for (int i = 0; i<size; ++i)
cout << "Value(" << i << ") = " << data[i] << endl;
return 0;
}
int main() {
cout << "template for sum()" << endl;
int a[] = {1, 2, 3};
double b[] = {2.1, 2.2, 2.3};
cout << sum(a,3) << endl;
cout << sum(b,3) << endl;
a[1] = 5;
b[1] = 5.5;
cout << sum(a,3) << endl;
cout << sum(b,3) << endl;
display(a, 3);
display(b, 3);
}