-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path安全数组类模板.cpp
90 lines (78 loc) · 1.64 KB
/
安全数组类模板.cpp
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
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
template<typename T>
class Array {
public:
T* data;
int size;
Array(int n) : size(n) {
data = new T[size];
}
~Array() {
delete[] data;
}
friend istream& operator>>(istream& in, Array<T>& arr) {
for (int i = 0; i < arr.size; i++) {
in >> arr.data[i];
}
return in;
}
friend ostream& operator<<(ostream& out, const Array<T>& arr) {
for (int i = 0; i < arr.size; i++) {
out << arr.data[i] << " ";
}
return out;
}
T& operator[](int i) {
if (i < 0 || i >= size) {
cout << "Out of boundary!" << endl;
exit(1);
}
return data[i];
}
void sort() {
std::sort(data, data + size);
}
int search(T e) const {
for (int i = 0; i < size; i++) {
if (data[i] == e) {
return i;
}
}
return -1;
}
};
template<typename T>
void Process(Array<T> &a) {
int pos;
T key;
cin >> a;
cout << a << endl;
a.sort();
cout << a << endl;
cin >> pos;
cout << a[pos] << endl;
cin >> key;
int index = a.search(key);
cout << index << endl;
}
int main() {
string type;
int n;
cin >> type >> n;
if (type == "int") {
Array<int> a(n);
Process(a);
} else if (type == "double") {
Array<double> a(n);
Process(a);
} else if (type == "string") {
Array<string> a(n);
Process(a);
} else {
cout << "Input error!" << endl;
}
return 0;
}