Find the smallest amongst 3 numbers in C++ [duplic

2020-02-08 06:58发布

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

标签: c++ max min
10条回答
Animai°情兽
2楼-- · 2020-02-08 07:47

A small modification

 int smallest(int x, int y, int z){
    int smallest = min(x,y);
    return min(smallest,z);
    }
查看更多
叛逆
3楼-- · 2020-02-08 07:48

You can store them in a vector and use std::min_element on that.

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());
查看更多
何必那么认真
4楼-- · 2020-02-08 07:52

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))
查看更多
劳资没心,怎么记你
5楼-- · 2020-02-08 07:55

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;
}
查看更多
登录 后发表回答