安全数组类模板

安全数组类模板 Description设计一个安全数组类模板ArrayT其中包含数组的输入、输出、排序和查找等方法使用三种类型的数据对其进行测试。1设计构造函数ArrayT::Array(int n)可动态分配n个T类型的存储空间2设计析构函数ArrayT::~Array()释放内存3重载输入流运算符istream operator(istream in, ArrayT arr)读入n个T类型数据4重载输出流运算符ostream operator(ostream out, const ArrayT arr)输出n个T类型数据5重载[]运算符若索引值i越界则输出“Out of boundary”并退出程序否则返回第i个数据元素6基于algorithm中的sort函数定义成员函数void ArrayT::sort()实现数组排序7设计成员函数int ArrayT::search(T e)const若查找成功返回非负索引值否则返回-18设计函数模板void Process(ArrayT a)用于测试数组类模板。main函数对应测试代码如下int main() { string type; int n; cin type n; if (typeint) { Arrayint a(n); Process(a); } else if (typedouble) { Arraydouble a(n); Process(a); } else if (typestring) { Arraystring a(n); Process(a); } else cout Input error! endl; return 0; }Input数据类型type和元素个数nn个数据元素索引值pos查找键值keyOutput排序前数据序列排序后数据序列索引值pos对应数据元素查找到的数据元素索引值Sample Input 1int 5 18 2 4 6 25 2 6Sample Output 118 2 4 6 25 2 4 6 18 25 6 2Sample Input 2double 6 24.5 3.6 18.3 96.4 102.56 88.1 3 102Sample Output 224.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 -1Sample Input 3string 7 dispose campus budget slip bacteria consume blast 7 campusSample Output 3dispose campus budget slip bacteria consume blast bacteria blast budget campus consume dispose slip Out of boundary!示例代码#include iostream #include string #include algorithm using namespace std; templatetypename T class Array { int size_; T *arr; public: Array(int n) : size_(n) { arr new T[n]; } ~Array() { delete[] arr; } int getsize() const { return size_; } templatetypename Ti friend istream operator(istream in, ArrayTi arr); templatetypename To friend ostream operator(ostream out, const ArrayTo arr); // 排序函数按题目要求命名为 sort void sort() { std::sort(arr, arr size_); } // 查找函数按题目要求命名为 search且为 const 成员 int search(const T e) const { for (int i 0; i size_; i) { if (arr[i] e) return i; } return -1; } T operator[](const int index) { if (index 0 || index size_) { cout Out of boundary! endl; exit(0); } return arr[index]; } }; // 输入运算符重载 templatetypename Ti istream operator(istream in, ArrayTi obj) { for (int i 0; i obj.getsize(); i) in obj.arr[i]; return in; } // 输出运算符重载 templatetypename To ostream operator(ostream out, const ArrayTo obj) { for (int i 0; i obj.getsize(); i) { if (i) out ; out obj.arr[i]; } return out; } // 测试函数模板 template typename T void Process(ArrayT a) { int pos; T e; cin a; // 读入数组 cout a endl; // 排序前 a.sort(); // 排序调用 sort cout a endl; // 排序后 cin pos; cout a[pos] endl; // 输出下标对应元素可能越界 cin e; cout a.search(e) endl; // 查找调用 search } int main() { string type; int n; cin type n; if (type int) { Arrayint a(n); Process(a); } else if (type double) { Arraydouble a(n); Process(a); } else if (type string) { Arraystring a(n); Process(a); } else { cout Input error! endl; } return 0; }