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;
}
apart min, that let you write return min(x, min(y, z)) there is ternary operator:
In your version, you're finding the smallest value only if it's smaller than 99999.
You should compare all three values together. Also, you're getting
int
but returningfloat
. 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:EDIT:
Two ways to improve the code into something that operates on a
vector
: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.
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
or
which stores the minimum of the variables
x
,y
andz
in the variableminimum
of typeT
(note thatx
,y
andz
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})
.Suppose,
1) Simple Solution:
2) Better Solution (in terms of optimization):
3) your solution Modified(Simple but not efficient):
4) Any number of Numbers: