实验13-函数模版与类模版-
题目描述
编写一个在数组中进行查找的函数模板,其中数组为具有n个元素,类型为T,要查找的元素为key。
注意:必须使用模板函数
输入
第一行输入t表示有t个测试实例
第二行先输入一个大写字母表示数组类型,I表示整数类型,D表示双精度数类型,C表示字符型,S表示字符串型;然后输入n表示数组长度。
第三行输入n个数据
第四行输入key
依次输入t个实例
输出
每行输出一个结果,找到输出key是数组中的第几个元素(从1开始),找不到输出0
输入样例
4
I 5
5 3 51 27 9
27
D 3
-11.3 25.42 13.2
2.7
C 6
a b g e u q
a
S 4
sandy david eason cindy
cindy
输出样例
4
0
1
4
#include<iostream>
using namespace std;
template<class Type>
class list
{
Type *a;
int n;
Type e;
public:
list(int len,Type *t,Type val)
{
n=len;e=val;
int i;
a=new Type[n];
for(i=0;i<n;i++)
a[i]=t[i];
}
void search()
{
int i,sum=0;
for(i=0;i<n;i++)
if(a[i]==e)
{
sum++;
cout<<i+1<<endl;
return;
}
if(sum==0)
cout<<"0"<<endl;
}
};
int main()
{
int t,n,i;
string type;
cin>>t;
while(t--)
{
cin>>type>>n;
if(type=="I")//int
{
int *a=new int[n];
for(i=0;i<n;i++)
cin>>a[i];
int e;
cin>>e;
//cout<<e<<endl;
list<int> L(n,a,e);
L.search();
}
else if(type=="D")//double
{
double *a=new double[n];
for(i=0;i<n;i++)
cin>>a[i];
double e;
cin>>e;
list<double> L(n,a,e);
L.search();
}
else if(type=="C")//char
{
char *a=new char[n];
for(i=0;i<n;i++)
cin>>a[i];
char e;
cin>>e;
list<char> L(n,a,e);
L.search();
}
else if(type=="S")//string
{
string *a=new string[n];
for(i=0;i<n;i++)
cin>>a[i];
string e;
cin>>e;
list<string> L(n,a,e);
L.search();
}
}
return 0;
}