13-C. 元素查找(函数模板)

实验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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值