#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;
}
温馨提示:答案为网友推荐,仅供参考