【问题标题】:Find the smallest amongst 3 numbers in C++ [duplicate]在C ++中找到3个数字中最小的[重复]
【发布时间】:2012-03-14 12:21:30
【问题描述】:

有什么方法可以让这个函数更优雅吗?我是 C++ 新手,我不知道是否有更标准化的方法来做到这一点。这可以变成一个循环,这样变量的数量就不会像我的代码那样受到限制吗?

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

【问题讨论】:

  • 哈哈,如果没有一个值小于 99999 怎么办?哈。
  • @jogojapan 或比以INT_MAX 开头更好(或std::numeric_limits&lt;int&gt;::max() 只需从第一个数字开头...
  • 由于 C++ 上下文,我不确定关闭它是否是个好主意。我想在引用的 dup 中看到一般性的讨论;而且我还希望看到有关模板和元编程的 C++ 讨论;以及与 constexpr 的 C++11 讨论。这看起来像是一个更好的 dup,即使它是 max 而不是 min: Most efficient way to find the greatest of three ints。它看起来更好,因为它特定于 C++。但它缺乏对模板、元编程和constexpr 的良好处理。
  • 我只是将最小值设置为第一个数字。不用担心溢出或选择最大的数字。
  • @L7ColWinters 是为了问题的目的。

标签: c++ max min


【解决方案1】:

如果可能,我建议使用 C++11 或更新版本,它允许您在不实现自己的函数的情况下计算所需的结果 (std::min)。正如在其中一个 cmets 中已经指出的那样,您可以这样做

T minimum(std::min({x, y, z}));

T minimum = std::min({x, y, z});

T类型的变量minimum中存储变量xyz中的最小值(注意xyz必须具有相同的类型或必须隐式转换为它)。相应地,同样可以得到最大值:std::max({x, y, z})

【讨论】:

  • 这应该是公认的答案。这是 C++11 如何让许多事情变得如此简单的一个例子,人们应该使用它,除非他们有非常好的理由。看看所有其他答案是多么复杂和不必要,尽管它是在 2012 年编写的,当时这种高级语法已经存在。
  • 我试过int x=1;int y=2; int z=3; std::cout &lt;&lt; std::max({x,y,z});,但它给出了一个编译错误。这样做的正确方法是什么?
  • 您可以在您的编译器上尝试使用标志 -std=c++11。
  • 您可能还需要#include &lt;algorithm&gt;,请参阅stackoverflow.com/q/44561919/150884
【解决方案2】:

可以进行许多改进。

您可以使用标准函数使其更清晰:

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

或者更好,正如 cmets 中指出的那样:

int smallest(int x, int y, int z){
    return std::min({x, y, z});
}

如果你想让它对任意数量的整数进行操作,你可以这样做:

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

你也可以让它通用,这样它就可以在任何类型上运行,而不仅仅是 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;
}

【讨论】:

  • 使用 C++11,std::min({x, y, z});.
  • 第三个示例可以使用迭代器编写,因此它也适用于其他容器,例如列表或集合。
  • 我要给你三个字:std::min_element
  • 请不要在这里使用数字限制的东西。只需将最小设置为第一个元素并从第二个元素开始检查。
  • @Tim:为什么?如果理由不明确,没有理由的意见是毫无价值的。这两种选择都有缺陷。
【解决方案3】:

除了 min,让你写 return min(x, min(y, z)) 还有三元运算符:

float smallest(int x, int y, int z){
  return x < y ? (x < z ? x : z) : (y < z ? y : z);
}

【讨论】:

    【解决方案4】:
    smallest=(x<((y<z)?y:z))?x:((y<z)?y:z);
    

    假设,

    x is one;
    y is two;
    z is three;
    
    smallest = (one < ((two < three) ? two:three)) ? one:((two < three) ? two:three)
    

    【讨论】:

    • 不知何故,在您的第一行中,在第二个结束括号处插入了一个“t”。
    【解决方案5】:

    有一个建议将其包含在N2485 下的 C++ 库中。这个提议很简单,所以我在下面包含了有意义的代码。显然,这假定了可变参数模板。

    template < typename T >
    const T & min ( const T & a )
    { return a ; }
    
    template < typename T , typename ... Args >
    const T & min ( const T & a , const T & b , const Args &... args )
    { return std :: min ( b < a ? b : a , args ...); }
    

    【讨论】:

      【解决方案6】:

      小改动

       int smallest(int x, int y, int z){
          int smallest = min(x,y);
          return min(smallest,z);
          }
      

      【讨论】:

        【解决方案7】:

        1) 简单的解决方案:

        int smallest(int x, int y, int z)
        {
            return std::min(std::min(x, y), z);
        }
        

        2) 更好的解决方案(在优化方面):

        float smallest(int x, int y, int z)
        {
          return x < y ? (x < z ? x : z) : (y < z ? y : z);
        }
        

        3)你的解决方案修改(简单但不高效):

        int smallest(int x, int y, int z)
        {
        
          int smallest = x;
        
          if (y < smallest)
             smallest=y;
          if(z < smallest)
             smallest=z;
          return smallest;
        }
        

        4) 任意数量的数字:

        对于 n 个数字,将其存储在一个数组 (array[n]) 中,对数组进行排序并 将数组[0] 取最小。

            //sort the elements in ascending order
            for(int i=0;i<n;i++)
            {
              if(array[i]>array[i+1])
              {
                int temp = array[i];
                array[i] = array[i+1];
                array[i+1] = temp;
              }
            }
        
            //display smallesst and largest
            cout<<"Smallest: "<<array[0];
            cout<<"Largest: "<<array[n-1];   //not needed in your case
            }
        

        【讨论】:

          【解决方案8】:

          在您的版本中,只有小于 99999 时才会找到最小值。

          您应该将所有三个值一起比较。此外,您收到int,但返回float。要么,您应该决定要处理哪种类型的值,或者您可以创建一个通用版本,适用于任何可以比较的类型:

          #include <algorithm>
          
          template<class T>
          T smallest(T x, T y, T z)
          {
            return std::min(x, std::min(y, z));
          }
          

          编辑:

          将代码改进为可在vector 上运行的东西的两种方法:

          #include <cstdio>
          #include <algorithm>
          #include <vector>
          
          // Use a built-in function to retrieve the smallest value automatically
          template<class T>
          T smallest1(const std::vector<T> &values)
          {
            return *std::min_element(values.begin(), values.end());
          }
          
          // Go through the vector manually
          template<class T>
          T smallest2(const std::vector<T> &values)
          {
            // Get the first value, to make sure we're comparing with an actual value
            T best_so_far = values.front();
            // For all the other values in the vector ...
            for(unsigned i = 1; i < values.size(); ++i) {
              // ... replace if the new one is better
              if(values[i] < best_so_far)
                best_so_far = values[i];
            }
            return best_so_far;
          }
          
          int main()
          {
            // Try out the code with a small vector
            std::vector<int> test;
            test.push_back(6);
            test.push_back(5);
            test.push_back(7);
          
            printf("%d\n", smallest1(test));
            printf("%d\n", smallest2(test));
          
            return 0;
          }
          

          【讨论】:

            【解决方案9】:

            或者你可以只使用define,来创建一个宏函数。

            #define min(x,y,z) (x < y ? (x < z ? x : z) : (y < z ? y : z))
            

            【讨论】:

            【解决方案10】:

            您可以将它们存储在向量中并在其上使用std::min_element

            例如:

            vector<int> values;
            values.push_back(10);values.push_back(1);values.push_back(12);
            
            int min = *std::min_element(values.begin(),values.end());
            

            【讨论】:

              猜你喜欢
              • 2017-05-30
              • 1970-01-01
              • 2013-11-10
              • 2021-06-14
              • 2011-08-13
              • 2016-08-06
              • 2011-10-11
              • 1970-01-01
              • 2021-02-04
              相关资源
              最近更新 更多