實現一個類模板,它可以接受一組數據,能對數據排序,也能輸出數組的內容。
每行輸入的第一個數字為0,1,2或3:為0時表示輸入結束; 為1時表示將輸入整數,為2時表示將輸入有一位小數的浮點數,為3時表示輸入字符。
如果第一個數字非0,則接下來將輸入一個正整數,表示即將輸入的數據的數量。
從每行第三個輸入開始,依次輸入指定類型的數據
測試程序:
#include <iostream>
using namespace std;
/* 請在這里填寫答案 */
template<class T>
MyArray<T>::~MyArray(){ delete[] data;}
template<class T>
bool MyArray<T>::check(){
int i;
for(i=0;i<size-1;i++)
if(data[i]>data[i+1]) { cout<<"ERROR!"<<endl;return false;}
return true;
}
int main( )
{
MyArray<int> *pI;
MyArray<float> *pF;
MyArray<char> *pC;
int ty, size;
cin>>ty;
while(ty>0){
cin>>size;
switch(ty){
case 1: pI = new MyArray<int>(size); pI->sort(); pI->check(); pI->display(); delete pI; break;
case 2: pF = new MyArray<float>(size); pF->sort(); pF->check(); pF->display(); delete pF; break;
case 3: pC = new MyArray<char>(size); pC->sort(); pC->check(); pC->display(); delete pC; break;
}
cin>>ty;
}
return 0;
}
答案:
1 template <class T> 2 class MyArray 3 { 4 T *data; 5 int size; 6 public: 7 MyArray(int size) //構造函數 8 { 9 this->size = size; 10 data = new T[size]; 11 12 for(int i(0); i < size; i++) 13 cin >> *(data + i); 14 }; 15 void sort() 16 { 17 T temp; 18 19 for(int i(0); i < size - 1; i++) //冒泡 20 for(int j(0); j < size - 1; j++) 21 if(*(data + j) > *(data + j + 1)) 22 { 23 temp = *(data + j); 24 *(data + j) = *(data + j + 1); 25 *(data + j + 1) = temp; 26 } 27 }; 28 void display() //輸出函數 29 { 30 for(int i(0); i < size - 1; i++) 31 cout << *(data + i) << " "; 32 33 cout << *(data + size - 1) << endl; 34 }; 35 ~MyArray(); 36 bool check(); 37 };
