c++中求最小值函数
时间: 2025-04-25 18:34:03 浏览: 19
### C++ 中求最小值的函数实现与使用
在 C++ 中,标准库提供了 `std::min` 函数来获取两个数中的较小者。此函数位于头文件 `<algorithm>` 中。
#### 使用 std::min 获取两个数值中的最小值
```cpp
#include <iostream>
#include <algorithm>
int main() {
int a = 10;
int b = 20;
// 调用 std::min 来比较两个整数并打印结果
std::cout << "The smaller number between " << a << " and " << b << " is: "
<< std::min(a, b) << '\n';
return 0;
}
```
对于多个参数的情况或者更复杂的数据结构(如数组),可以通过循环调用 `std::min` 或者利用其他算法来进行处理。
#### 自定义模板函数实现求数组中最小值的功能
当需要找到一组数据中的最小元素时,可以创建自定义模板函数:
```cpp
template<typename T>
T findMin(const T* array, size_t length) {
if (length == 0) throw std::invalid_argument("Array cannot be empty");
T minElement = array[0];
for(size_t i=1 ;i<length;i++){
minElement = std::min(minElement,array[i]);
}
return minElement;
}
// 测试该功能
int testFindMin(){
double data[] = {3.7, 2.0, -1.5, 8.9};
try{
std::cout<<"Minimum element in the given array is:"<<findMin(data,sizeof(data)/sizeof(double))<<'\n';
}
catch(std::exception& e){
std::cerr<<e.what()<<'\n';
}
return 0;
}
```
上述代码展示了如何通过遍历整个数组并与当前已知最小值对比的方式找出其中的最小项[^1]。
阅读全文
相关推荐


















