用c++语言编写一个函数模板findmin(...),使该函数能寻找数组中最小元素,将该元素的下标通过参数返回,函数返回值为其地址值,考虑整型、小数等不同类型的数组
时间: 2024-02-15 20:01:42 浏览: 76
好的,下面是我为您编写的代码:
```cpp
template<typename T>
T* findmin(T* arr, int size, int& index)
{
if(size <= 0) return nullptr;
index = 0;
T* min = &arr[0];
for(int i = 1; i < size; ++i)
{
if(arr[i] < *min)
{
min = &arr[i];
index = i;
}
}
return min;
}
```
这个函数模板可以寻找任意类型的数组中最小元素,并将其下标通过引用参数返回。函数返回值为最小元素的地址。
使用示例:
```cpp
int main()
{
int int_arr[] = {5, 2, 9, 1, 7};
int int_index;
int* int_min_ptr = findmin(int_arr, 5, int_index);
cout << "The minimum value is " << *int_min_ptr << ", and its index is " << int_index << endl;
double double_arr[] = {3.14, 1.23, 2.71, 0.99};
int double_index;
double* double_min_ptr = findmin(double_arr, 4, double_index);
cout << "The minimum value is " << *double_min_ptr << ", and its index is " << double_index << endl;
return 0;
}
```
输出结果:
```
The minimum value is 1, and its index is 3
The minimum value is 0.99, and its index is 3
```
阅读全文