编写一个在数组中进行查找的函数模板,其中数组为具有n个元素,类型为T,要查找的元素为key。 注意:必须使用模板函数第一行输入t表示有t个测试实例 第二行先输入一个大写字母表示数组类型,I表示整数类型,D表示双精度数类型,C表示字符型,S表示字符串型;然后输入n表示数组长度。 第三行输入n个数据 第四行输入key 依次输入t个实例
时间: 2024-03-07 13:46:31 浏览: 26
好的,以下是根据您的要求编写的函数模板代码:
```c++
#include<iostream>
#include<string>
using namespace std;
template<typename T>
int searchElement(T arr[], int n, T key)
{
for(int i=0; i<n; i++)
{
if(arr[i] == key)
return i;
}
return -1;
}
int main()
{
int t;
cin >> t;
while(t--)
{
char type;
int n;
cin >> type >> n;
if(type == 'I')
{
int arr[n], key;
for(int i=0; i<n; i++)
cin >> arr[i];
cin >> key;
cout << searchElement(arr, n, key) << endl;
}
else if(type == 'D')
{
double arr[n], key;
for(int i=0; i<n; i++)
cin >> arr[i];
cin >> key;
cout << searchElement(arr, n, key) << endl;
}
else if(type == 'C')
{
char arr[n], key;
for(int i=0; i<n; i++)
cin >> arr[i];
cin >> key;
cout << searchElement(arr, n, key) << endl;
}
else if(type == 'S')
{
string arr[n], key;
for(int i=0; i<n; i++)
cin >> arr[i];
cin >> key;
cout << searchElement(arr, n, key) << endl;
}
}
return 0;
}
```
在这个模板函数中,我们先读入一个整数 `t`,表示测试实例的数量。接下来,对于每一个测试实例,我们先读入一个字符 `type`,表示数组元素类型,然后读入一个整数 `n`,表示数组长度。接下来,根据读入的 `type`,我们分别定义一个对应类型的数组 `arr`,并读入 `n` 个数组元素。最后,我们读入需要查找的关键字 `key`,并调用 `searchElement` 函数在数组中查找该元素,并输出其下标。
需要注意的是,在这个模板函数中,我们需要对每一种类型的数组分别进行处理,这部分代码比较冗长,但是可以通过使用 C++ 17 中的 if constexpr 来简化代码。
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)