C++编写一个模板函数程序,查找数组内容,调用函数时,数组类型可以是整型也可以是双精度型。
时间: 2024-05-11 09:19:04 浏览: 19
以下是一个示例代码,实现查找数组中是否存在指定的元素,并返回元素在数组中的索引位置(若不存在则返回-1)。
```c++
#include <iostream>
using namespace std;
template <typename T>
int findElement(T arr[], int size, T element) {
for (int i = 0; i < size; i++) {
if (arr[i] == element) {
return i;
}
}
return -1;
}
int main() {
int intArr[] = {1, 2, 3, 4, 5};
double doubleArr[] = {1.1, 2.2, 3.3, 4.4, 5.5};
int intElement = 3;
double doubleElement = 4.4;
int intIndex = findElement(intArr, 5, intElement);
double doubleIndex = findElement(doubleArr, 5, doubleElement);
cout << "intIndex: " << intIndex << endl;
cout << "doubleIndex: " << doubleIndex << endl;
return 0;
}
```
在上述代码中,我们定义了一个模板函数 `findElement`,该函数接受三个参数:数组 `arr`、数组大小 `size` 和待查找的元素 `element`。该函数会遍历整个数组,查找是否存在指定的元素,若找到则返回该元素在数组中的索引位置,否则返回-1。
在 `main` 函数中,我们声明了两个数组 `intArr` 和 `doubleArr`,分别为整型和双精度型。然后定义了两个待查找的元素 `intElement` 和 `doubleElement`,并调用模板函数 `findElement` 查找它们在数组中的索引位置。最后将查找结果输出到控制台。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)