编写c++函数模板求出三个元素里面最小的两个
时间: 2024-10-24 14:16:48 浏览: 28
在C++中,我们可以编写一个函数模板来找出给定的三个元素中最小的两个。这里是一个简单的示例:
```cpp
template <typename T>
T findTwoSmallest(T a, T b, T c) {
if (a <= b && a <= c) {
return a;
} else if (b <= a && b <= c) {
return b;
} else {
return c;
}
}
// 使用这个模板函数
int main() {
int min1 = findTwoSmallest(5, 3, 7); // 返回3
double smallest = findTwoSmallest(3.14, 2.71, 4.20); // 返回2.71
std::cout << "The two smallest elements are: " << min1 << " and " << smallest << std::endl;
return 0;
}
```
在这个`findTwoSmallest`函数模板中,我们首先比较三个参数,如果a是最小的,就直接返回;如果是b或c更小,我们就依次检查并返回。这样,不论传入的是整数、浮点数还是其他满足模板类型的值,函数都能正确找到其中的两个最小值。
阅读全文
相关推荐

















