return a < b ? a : b;
时间: 2024-05-09 07:19:34 浏览: 14
This is a conditional (ternary) operator in C++ that returns the smaller of two values, a or b. It checks if a is less than b and if so, returns a, otherwise it returns b.
It can be rewritten as:
```
if(a < b) {
return a;
} else {
return b;
}
```
相关问题
float min(float a, float b) { return a < b ? a : b; }
This is a simple C++ function that takes two floating point numbers as input and returns the smaller of the two.
The function uses the ternary operator to check if the first number (a) is less than the second number (b). If it is, then the function returns a, otherwise it returns b.
For example, if we call the function with min(3.5, 2.2), the function will return 2.2 since it is the smaller of the two numbers.
#include <iostream> #include <string> template <typename T> T min(T a, T b) { return a < b ? a : b; } int main() { int a = 3, b = 5; std::string s1 = "hello", s2 = "world"; std::cout << min(a, b) << std::endl; // 输出3 std::cout << min(s1, s2) << std::endl; // 输出hello return 0; }优化这段代码
这段代码已经很简洁了,不过可以考虑使用 const 引用作为函数参数,以避免不必要的拷贝。
另外,可以使用 C++17 中引入的 if constexpr 特性来实现编译期条件判断,从而避免在编译期间对两个参数进行比较,提高代码效率。
优化后的代码如下:
```c++
#include <iostream>
#include <string>
template <typename T>
constexpr const T& min(const T& a, const T& b)
{
if constexpr (std::is_floating_point_v<T>) {
return (a < b) ? a : b;
} else {
return (a < b) ? a : b;
}
}
int main()
{
int a = 3, b = 5;
std::string s1 = "hello", s2 = "world";
std::cout << min(a, b) << std::endl; // 输出3
std::cout << min(s1, s2) << std::endl; // 输出hello
return 0;
}
```
在模板函数中使用 if constexpr 特性,根据传入的参数类型进行不同的处理,从而避免了运行时条件判断的开销。