安全数组类模板
Description
设计一个安全数组类模板Array<T>,其中包含数组的输入、输出、排序和查找等方法,使用三种类型的数据对其进行测试。
(1)设计构造函数Array<T>::Array(int n),可动态分配n个T类型的存储空间;
(2)设计析构函数Array<T>::~Array()释放内存;
(3)重载输入流运算符istream &operator>>(istream& in, Array<T>& arr)读入n个T类型数据;
(4)重载输出流运算符ostream &operator<<(ostream& out, const Array<T>& arr)输出n个T类型数据;
(5)重载[]运算符,若索引值i越界,则输出“Out of boundary”并退出程序,否则返回第i个数据元素;
(6)基于<algorithm>中的sort函数定义成员函数void Array<T>::sort(),实现数组排序;
(7)设计成员函数int Array<T>::search(T e)const,若查找成功返回非负索引值,否则返回-1;
(8)设计函数模板void Process(Array<T> &a)用于测试数组类模板。
main函数对应测试代码如下:
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;
}
Input
数据类型type和元素个数n
n个数据元素
索引值pos
查找键值key
Output
排序前数据序列
排序后数据序列
索引值pos对应数据元素
查找到的数据元素索引值
Sample Input 1
int 5 18 2 4 6 25 2 6
Sample Output 1
18 2 4 6 25 2 4 6 18 25 6 2
Sample Input 2
double 6 24.5 3.6 18.3 96.4 102.56 88.1 3 102
Sample Output 2
24.5 3.6 18.3 96.4 102.56 88.1 3.6 18.3 24.5 88.1 96.4 102.56 88.1 -1
Sample Input 3
string 7 dispose campus budget slip bacteria consume blast 7 campus
Sample Output 3
dispose campus budget slip bacteria consume blast bacteria blast budget campus consume dispose slip Out of boundary!
代码:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
template <class T>
class Array {
private:
T* data;
int size;
public:
Array(int size = 0) : size(size) {
data = new T[size];
}
~Array() {
delete[] data;
}
friend istream& operator>>(istream& in, Array<T>& a) {
for (int i = 0; i < a.size; i++) {
in >> a.data[i];
}
return in;
}
friend ostream& operator<<(ostream& out, const Array<T>& a) {
for (int i = 0; i < a.size; i++) {
out << a.data[i];
if (i < a.size - 1) out << " ";
}
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 x) const {
for (int i = 0; i < size; i++) {
if (data[i] == x) {
return i;
}
}
return -1;
}
int getSize() const {
return size;
}
};
template <class T>
void Process(Array<T>& a) {
cin >> a;
cout << a << endl;
a.sort();
cout << a << endl;
int pos;
cin >> pos;
if (pos >= 0 && pos < a.getSize()) {
cout << a[pos] << endl;
}
else {
cout << "Out of boundary!" << endl;
return;
}
T key;
cin >> key;
int result = a.search(key);
cout << result << 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;
}