设计一个一维数组的类模板,要求有对数组进行排序、查找和求元素总和的 成员函数

并在主函数中使用基本数据类型和自定义类类型来实例化。

#include<iostream>
using namespace std;

//类模板
template<class T>
class vector
{
public:
void sort(T a[],int n);
T sum(T a[],int n);
int search(T e, T a[], int n);
};

//排序
template<class T>
void vector<T>::sort(T a[],int n)
{
T temp;
bool exchange;
for(int i = 1; i < n; i++)
{
exchange = false;
for(int j = n-1; j >= i; j--)
if(a[j] < a[j-1])
{
temp = a[j]; a[j] = a[j-1]; a[j-1] = temp;
exchange = true;
}
if(!exchange)
return;
}
}

//求和
template<class T>
T vector<T>::sum(T a[],int n)
{
T sum = a[0];
for(int i = 1; i < n; i++)
sum += a[i];
return sum;
}

//查找
template<class T>
int vector<T>::search(T e, T a[], int n)
{
for(int i = 0; i < n; i++)
if(a[i] == e)
return i;
return -1;
}

void main()
{
int data[5] = {5,4,3,2,1};
vector<int> obj;

cout<<"数组和为:"<<obj.sum(data,5)<<endl;
cout<<"数字4在数组中的位置是:"<<obj.search(4,data,5)<<endl;

cout<<"排序前数组各元素为:"<<endl;
for(int i = 0; i < 5; i++)
cout<<data[i]<<" ";
cout<<endl;

cout<<"排序后数组各元素为:"<<endl;
for(i = 0; i < 5; i++)
cout<<data[i]<<" ";
cout<<endl;
}
温馨提示:答案为网友推荐,仅供参考
相似回答