编写一个程序,使用类模板对数组元素进行排序,倒置、查找和求和
要求:具有对数组元素进行排序,倒置、查找和求和功能,然后产生类型实参分别为int型和double型的两个模板类,分别对整型数组与双精度数组完成所要求的操作
shuzucaozuo.h
#include <iostream>
using namespace std;
const int maxsize = 100;
template <typename T>
class A
{
private:
T a[maxsize];
int m_len;
public:
void print(T *c);
A(int len, T *b);
~A() {}
void sort();
void reverse();
void search(T flag);
void sum();
};
shuzucaozuo.cpp
#include "shuzucaozuo.h"
template class A<int>; //显式实例化
template class A<double>;
template <typename T>
A<T>::A(int len, T *b)
{
m_len = len;
for (int i = 0; i < len; i++)
{
a[i] = b[i];
}
print(a);
}
template <typename T>
void A<T>::sort()
{
T temp;
T a1[maxsize];
for (int i = 0; i < m_len; i++)
{
a1[i] = a[i];
}
for (int i = 0; i < m_len - 1; i++)
{
for (int i = 0; i < m_len - 1; i++)
{
if (a1[i] > a1[i + 1])
{
temp = a1[i];
a1[i] = a1[i + 1];
a1[i + 1] = temp;
}
}
}
print(a1);
}
template <typename T>
void A<T>::print(T *c)
{
for (int i = 0; i < m_len; i++)
{
cout << c[i] << " ";
}
cout << endl;
}
template <typename T>
void A<T>::reverse()
{
T a2[maxsize];
for (int i = 0; i < m_len; i++)
{
a2[i] = a[m_len - i - 1];
}
print(a2);
}
template <typename T>
void A<T>::search(T flag)
{
int temp = 0;
for (int i = 0; i < m_len; i++)
{
if (flag == a[i])
{
cout << "查找成功! " << flag << "是第" << i + 1 << "个元素!" << endl;
temp = 1;
break;
}
}
if (0 == temp)
{
cout << "查找失败!该元素不存在!" << endl;
}
}
template <typename T>
void A<T>::sum()
{
T total = 0;
for (int i = 0; i < m_len; i++)
{
total += a[i];
}
cout << "数组之和为" << total << endl;
}
main.cpp
#include "shuzucaozuo.h"
int main()
{
int int_len;
int double_len;
int int_flag;
double double_flag;
int *a;
double *b;
cout << "请输入两种类型数组的元素个数:" << endl;
cin >> int_len >> double_len;
a = new int[int_len];
b = new double[double_len];
cout << "请输入int型数组的元素" << endl;
for (int i = 0; i < int_len; i++)
{
cin >> a[i];
}
cout << "请输入double型数组的元素" << endl;
for (int i = 0; i < double_len; i++)
{
cin >> b[i];
}
// int型数组操作
cout << "int型数组为:" << endl;
A<int> int_a(int_len, a);
cout << "排序操作:" << endl;
int_a.sort();
cout << "倒序操作:" << endl;
int_a.reverse();
cout << "查找操作:" << endl;
cout << "输入要查找的元素:" << endl;
cin >> int_flag;
int_a.search(int_flag);
cout << "求和操作:" << endl;
int_a.sum();
// double型数组操作
cout << "double型数组为:" << endl;
A<double> double_a(double_len, b);
cout << "排序操作:" << endl;
double_a.sort();
cout << "倒序操作:" << endl;
double_a.reverse();
cout << "查找操作:" << endl;
cout << "输入要查找的元素:" << endl;
cin >> double_flag;
double_a.search(double_flag);
cout << "求和操作:" << endl;
double_a.sum();
return 0;
}