在 C++ 中找到 3 个数字中最小的一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9424173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find the smallest amongst 3 numbers in C++
提问by user1145538
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?
有没有办法让这个功能更优雅?我是 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;
}
回答by Alex
There's a number of improvements that can be made.
可以进行许多改进。
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});
}
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;
}
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;
}
回答by Gerald Senarclens de Grancy
If possible, I recommend using C++11 or newer which allows you to compute the desired result w/out implementing your own function (std::min). As already pointed out in one of the comments, you can do
如果可能,我建议使用 C++11 或更高版本,它允许您在不实现自己的函数(std::min)的情况下计算所需的结果。正如其中一条评论中已经指出的那样,您可以这样做
T minimum(std::min({x, y, z}));
or
或者
T minimum = std::min({x, y, z});
which stores the minimum of the variables x
, y
and z
in the variable minimum
of type T
(note that x
, y
and z
must have the same type or have to be implicitly convertible to it). Correspondingly, the same can be done to obtain a maximum: std::max({x, y, z})
.
它存储变量的最小值x
,y
并且z
在minimum
类型的变量中T
(注意x
,y
和z
必须具有相同的类型或必须隐式转换为它)。相应地,同样可以得到最大值:std::max({x, y, z})
。
回答by CapelliC
apart min, that let you write return min(x, min(y, z)) there is ternary operator:
除了 min,让你写 return min(x, min(y, z)) 有三元运算符:
float smallest(int x, int y, int z){
return x < y ? (x < z ? x : z) : (y < z ? y : z);
}
回答by Martin James
smallest=(x<((y<z)?y:z)t)?x:((y<z)?y:z);
Suppose,
认为,
x is one;
y is two;
z is three;
smallest = (one < ((two < three) ? two:three)) ? one:((two < three) ? two:three)
回答by sank
A small modification
一个小修改
int smallest(int x, int y, int z){
int smallest = min(x,y);
return min(smallest,z);
}
回答by tgoodhart
There is a proposal to include this into the C++ library under N2485. The proposal is simple, so I've included the meaningful code below. Obviously this assumes variadic templates.
有一项建议将其包含在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 ...); }
回答by Anders Sj?qvist
In your version, you're finding the smallest value only if it's smaller than 99999.
在您的版本中,只有当它小于 99999 时,您才会找到最小值。
You should compare all three values together. Also, you're getting int
but returning float
. Either, you should decide which kind of values you want to process, or you could create a generalized version that works with any kind that can be compared:
您应该将所有三个值一起比较。此外,您正在获取int
但返回float
. 或者,您应该决定要处理哪种类型的值,或者您可以创建一个通用版本,适用于任何可以比较的类型:
#include <algorithm>
template<class T>
T smallest(T x, T y, T z)
{
return std::min(x, std::min(y, z));
}
EDIT:
编辑:
Two ways to improve the code into something that operates on a vector
:
将代码改进为对 a 进行操作的两种方法vector
:
#include <cstdio>
#include <algorithm>
#include <vector>
// Use a built-in function to retrieve the smallest value automatically
template<class T>
T smallest1(const std::vector<T> &values)
{
return *std::min_element(values.begin(), values.end());
}
// Go through the vector manually
template<class T>
T smallest2(const std::vector<T> &values)
{
// Get the first value, to make sure we're comparing with an actual value
T best_so_far = values.front();
// For all the other values in the vector ...
for(unsigned i = 1; i < values.size(); ++i) {
// ... replace if the new one is better
if(values[i] < best_so_far)
best_so_far = values[i];
}
return best_so_far;
}
int main()
{
// Try out the code with a small vector
std::vector<int> test;
test.push_back(6);
test.push_back(5);
test.push_back(7);
printf("%d\n", smallest1(test));
printf("%d\n", smallest2(test));
return 0;
}
回答by Rohit Vipin Mathews
1) Simple Solution:
1)简单的解决方案:
int smallest(int x, int y, int z)
{
return std::min(std::min(x, y), z);
}
2) Better Solution (in terms of optimization):
2)更好的解决方案(在优化方面):
float smallest(int x, int y, int z)
{
return x < y ? (x < z ? x : z) : (y < z ? y : z);
}
3) your solution Modified(Simple but not efficient):
3)您的解决方案已修改(简单但效率不高):
int smallest(int x, int y, int z)
{
int smallest = x;
if (y < smallest)
smallest=y;
if(z < smallest)
smallest=z;
return smallest;
}
4) Any number of Numbers:
4) 任意数量的数字:
For n numbers, store it in an array (array[n]), Sort the array and take the array[0] to get smallest.
对于n个数字,将其存储在一个数组(数组[n])中,对数组进行排序并取数组[0]最小。
//sort the elements in ascending order
for(int i=0;i<n;i++)
{
if(array[i]>array[i+1])
{
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
//display smallesst and largest
cout<<"Smallest: "<<array[0];
cout<<"Largest: "<<array[n-1]; //not needed in your case
}
回答by Iuliu
Or you can just use define, to create a macro function.
或者你可以只使用定义来创建一个宏函数。
#define min(x,y,z) (x < y ? (x < z ? x : z) : (y < z ? y : z))
回答by user3926526
You can store them in a vector and use std::min_element
on that.
您可以将它们存储在向量中并std::min_element
在其上使用。
For example:
例如:
vector<int> values;
values.push_back(10);values.push_back(1);values.push_back(12);
int min = *std::min_element(values.begin(),values.end());