Find the smallest amongst 3 numbers in C++

user1145538 picture user1145538 · Feb 24, 2012 · Viewed 102k times · Source

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;
}

Answer

Gerald Senarclens de Grancy picture Gerald Senarclens de Grancy · Jul 30, 2014

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