-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TemplateFunctions.h
103 lines (82 loc) · 2.21 KB
/
TemplateFunctions.h
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#pragma once
template <typename T>
void sort(T array[], int size) // îáúÿâëåíèå è îïðåäåëåíèå
{
T t;
for (int i = 0; i < size - 1; i++)
for (int j = size - 1; j > i; j--)
if (array[j] < array[j - 1])
{
t = array[j];
array[j] = array[j - 1];
array[j - 1] = t;
}
}
template<int BufferSize> // öåëî÷èñëåííûé ïàðàìåòð
char* read()
{
char* Buffer = new char[BufferSize];
return Buffer;
}
/*
int ar[5] = { 5, 4, 3, 2, 1 };
sort<int>(ar, 5);
sort(ar, 5); // Âûâåäåíèå çíà÷åíèé ïàðàìåòðîâ
// êîìïèëÿòîð ìîæåò ñàì âûâåñòè (ëîãè÷åñêè îïðåäåëèòü) çíà÷åíèå ïàðàìåòðà øàáëîíà ôóíêöèè
// èç àðãóìåíòà ôóíêöèè. Íàïðèìåð, ïðè âûçîâå ôóíêöèè sort íåîáÿçàòåëüíî óêàçûâàòü
// ïàðàìåòð øàáëîíà (åñëè îí ñîâïàäàåò ñ òèïîì ýëåìåíòîâ àðãóìåíòà - ìàññèâà)
char c[] = "abdec";
sort<char>(c, strlen(c));
//sort<int>(c, 5); // îøèáêà! ó sort<int> ïàðàìåòð int[], à íå char[]
for (int i = 0; i < 5; i++)
cout << ar[i] << " - " << c[i] << "\n";
char* ReadString = read<20>();
delete[] ReadString;
ReadString = read<30>();
*/
// ===================================================================================
template <class T>
T Max(T a, T b)
{
if (a > b) return a;
else return b;
}
/*
cout << Max(12, 100) << endl;
cout << Max(12.33, 3.0) << endl;
// cout << Max(12.33, 3) << endl; // îøèáêà! ïàðàìåòð "T" íåîäíîçíà÷åí!
*/
// ===================================================================================
template <class T>
void MySwap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
/*
int x = 5, y = 10;
MySwap(x, y);
cout << x << " " << y << "\n";
COORD a{ 1, 1 }, b{ 2, 2 };
MySwap(a, b);
cout << "[" << a.X << ", " << a.Y << "], [" << b.X << ", " << b.Y << "]\n";
*/
// ===================================================================================
template <typename T, int N>
double avg(T(&ar)[N])
{
double sum = 0;
for (int i = 0; i < N; i++)
sum += ar[i];
return sum / N;
}
/*
double arrayDouble[3] = { 4.5, 6.7, 9.0 };
cout << avg(arrayDouble) << endl;
int arrayInt[5] = { 1, 5, 9, 10, 12 };
cout << avg(arrayInt) << endl;
char arrayChar[4] = { 'A', 'B', 'B', 'C' };
cout << (char)avg(arrayChar) << endl;
auto& sm = arrayInt; // ref to array!
int(&sm2)[5] = arrayInt;
*/