本文介绍了在C ++中找到3个数字中的最小数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以使此功能更优雅?我是C ++的新手,我不知道是否有更标准化的方法来执行此操作.可以把它变成一个循环,这样变量的数量就不会像我的代码那样受到限制吗?
Is there any way to make this function more elegant? I'm new to C++, I don't know if there is a more standardized way to do this. Can this be turned into a loop so the number of variables isn't restricted as with my code?
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; }推荐答案
可以进行许多改进.
您可以使用标准功能使其更清晰:
You could use standard functions to make it clearer:
// 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); }或者如评论中所指出的那样更好:
Or better still, as pointed out in the comments:
int smallest(int x, int y, int z){ return std::min({x, y, z}); }如果您希望它可以在任意数量的int上运行,则可以执行以下操作:
If you want it to operate on any number of ints, you could do something like this:
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; }您还可以使其通用,使其可以在任何类型上运行,而不仅仅是ints
You could also make it generic so that it'll operate on any type, instead of just ints
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; }更多推荐
在C ++中找到3个数字中的最小数字
发布评论