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; }
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
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}).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With