1、编写一个使用类模板对数组中元素进行排序和求和的程序。
【提示】在模板中完成排序和求和的操作。
#include
using namespace std;
//类模板
template
class vector
{
public:
void sort(T a[],int n);
T sum(T a[],int n);
int search(T e, T a[], int n);
};
//排序
template
void vector::sort(
2、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;
3、 }
if(!exchange)
return;
}
}
//求和
template
T vector::sum(T a[],int n)
{
T sum = a[0];
for(int i = 1; i < n; i++)
sum += a[i];
return sum;
}
//查找
template
int vector::search(T e, T a[], int n)
{
4、 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 obj;
cout<<"数组和:"<5、or(int i = 0; i < 5; i++)
cout<6、板,完成如下功能:
(1) 数组的规模可以任意类型,任意大小。
(2) 重载构造函数实现不同种的初始化方式(自拟)。
(3) 数组排序函数。
(4) 数组查找函数。
(5) 数组查找最大值/最小值函数。
(6) 对运算符[]重载,支持对该数组类模板对象的下标运算
#include
#include
using namespace std;
//模版类定义,一个是虚拟类型T,用来给定数组元素的类型,一个是整型值size,用来给定数组的大小,即元素个数
//此类是一个万能数组,数组类型可以
7、任意给定,数组大小可任意给定
//模板类不仅可以传递类型T,也可以传递数值size
template
class Array
{
public:
Array()
{
int i;
cout<<"请输如"<>array[i];
8、 }
void display()
{
int i;
cout<<"输出"< arr
9、ay_int; //给出模板的参数化值,使其生成具体类,然后定义类对象
//当前数组类中数组元素类型为int,数组大小为5
array_int.display();
Array array_char; //给出模板的参数化值,使其生成具体类,然后定义类对象
//当前数组类中数组元素类型为char,数组大小为3
array_char.display();
Array array_float; //给出模板的参数化值,使其生成具体类,然后定义类对象
//当前数组类中数组元素类型为int,数组大小为5
array_float.display();
return 0;
}