有没有办法让这个功能更优雅?我是C++的新手,我不知道是否有更标准化的方法来做到这一点.这可以变成一个循环,所以变量的数量不受我的代码限制吗?
float smallest(int x, int y, int z) {
int smallest = 99999;
if (x < smallest)
smallest=x;
if (y < smallest)
smallest=y;
if(z < smallest)
smallest=z;
return smallest;
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*lex 43
可以进行许多改进.
您可以使用标准函数使其更清晰:
// Notice I made the return type an int instead of a float,
// since you're passing in ints
int smallest(int x, int y, int z){
return std::min(std::min(x, y), z);
}
Run Code Online (Sandbox Code Playgroud)
或者更好的是,正如评论中所指出的那样:
int smallest(int x, int y, int z){
return std::min({x, y, z});
}
Run Code Online (Sandbox Code Playgroud)
如果您希望它以任意数量的整数运行,您可以执行以下操作:
int smallest(const std::vector<int>& intvec){
int smallest = std::numeric_limits<int>::max(); // Largest possible integer
// there are a number of ways to structure this loop, this is just one
for (int i = 0; i < intvec.size(); ++i)
{
smallest = std::min(smallest, intvec[i]);
}
return smallest;
}
Run Code Online (Sandbox Code Playgroud)
你也可以使它成为通用的,这样它就可以在任何类型上运行,而不仅仅是整数
template <typename T>
T smallest(const std::vector<T>& vec){
T smallest = std::numeric_limits<T>::max(); // Largest possible integer
// there are a number of ways to structure this loop, this is just one
for (int i = 0; i < vec.size(); ++i)
{
smallest = std::min(smallest, vec[i]);
}
return smallest;
}
Run Code Online (Sandbox Code Playgroud)
Ger*_*ncy 39
如果可能的话,我建议使用C++ 11或更新版本,它允许您计算所需的结果,而不是实现您自己的函数(std :: min).正如其中一条评论中已经指出的那样,你可以做到
T minimum(std::min({x, y, z}));
Run Code Online (Sandbox Code Playgroud)
要么
T minimum = std::min({x, y, z});
Run Code Online (Sandbox Code Playgroud)
其最小的变量存储x,y并z在可变minimum型的T(注意x,y与z必须具有相同的类型或必须隐式转换到它).相应地,可以做同样的事情来获得最大值:std::max({x, y, z}).
Cap*_*liC 10
min min,让你写返回min(x,min(y,z))有三元运算符:
float smallest(int x, int y, int z){
return x < y ? (x < z ? x : z) : (y < z ? y : z);
}
Run Code Online (Sandbox Code Playgroud)
有人建议将其包含到N2485下的 C++ 库中。该提案很简单,因此我在下面包含了有意义的代码。显然,这假设了可变参数模板。
template < typename T >
const T & min ( const T & a )
{ return a ; }
template < typename T , typename ... Args >
const T & min ( const T & a , const T & b , const Args &... args )
{ return std :: min ( b < a ? b : a , args ...); }
Run Code Online (Sandbox Code Playgroud)
smallest=(x<((y<z)?y:z)t)?x:((y<z)?y:z);
Run Code Online (Sandbox Code Playgroud)
假设,
x is one;
y is two;
z is three;
smallest = (one < ((two < three) ? two:three)) ? one:((two < three) ? two:three)
Run Code Online (Sandbox Code Playgroud)
一个小修改
int smallest(int x, int y, int z){
int smallest = min(x,y);
return min(smallest,z);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
80382 次 |
| 最近记录: |