Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the smallest amongst 3 numbers in C++ [duplicate]

Tags:

c++

max

min

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; } 
like image 873
user1145538 Avatar asked Feb 24 '12 01:02

user1145538


1 Answers

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}).

like image 60
Gerald Senarclens de Grancy Avatar answered Sep 21 '22 11:09

Gerald Senarclens de Grancy