【问题标题】:How to find the min and max in a vector<double> without using min_element C++如何在不使用 min_element C++ 的情况下找到 vector<double> 中的最小值和最大值
【发布时间】:2014-02-14 20:52:37
【问题描述】:

我有一个向量,它包含用户输入的元素数量。如果用户输入 4 double,它将有 4;等等

我是 C++ 编程的新手,我正试图通过迭代每个元素并确定向量中的最小和最大双精度来找出如何使用 for 循环的方法。我很困惑,因为我们不知道向量的长度是多少,所以我不确定如何解决这个问题。我想从向量中找到最大/最小值以及它们的索引是什么。

vector<double> numbers;
double n;
std::cout << "Enter in numbers :";
std::getline(std::cin, n);
numbers.push_back(n);

【问题讨论】:

  • numbers.size() 给你长度。
  • 仅供参考,如果您想同时找到最小和最大元素,minmax_element 可以做到这一点。

标签: c++ vector double max min


【解决方案1】:
size_t iMax=0,iMin=0;
for(size_t i=1; i<x.size(); ++i)
{
        if(x[iMax] < x[i])
                iMax=i;
        if(x[iMin] > x[i])
                iMin=i;
}
//iMax is index of the biggest num in the array

【讨论】:

    【解决方案2】:

    您可以使用std::set&lt;double&gt;

    std::set<double> numbers;
    
    double minValue = *numbers.begin();
    double maxValue = *numbers.rbegin();
    

    【讨论】:

      【解决方案3】:

      未经测试,但这应该会在您的向量中找到最大值。

      int max = 0;
      if (!numbers.isEmpty())
          max = numbers[0]; //if its not empty, start it at the first element.
                            //this ensures that your max is never HIGHER
                            //than the largest element
      for(int i = 0; i < numbers.size(); i++) {
          if(numbers[i] > max)
              max = numbers[i]; //replace the old max if the current element is higher
      }
      

      【讨论】:

        【解决方案4】:

        如果您使用的是 C++ 11,还有另一个更简单的解决方案:

        double max(vector<double> n)
        {
             double max = n[0] ;
        
             for(double i : n)
                  if(i > max)
                       max = i ;
        
             return max ;
        }
        

        参考: http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html

        【讨论】:

        • 这里假设n中有第一个元素,可能不是这样。
        【解决方案5】:

        使用vector&lt;double&gt;::iterator 类型的迭代器。然后,您可以使用指针加法来遍历向量,直到您点击 vector.end()(位于向量的最后一个元素之后)。

        double max(vector<double> n)
        {
             double max = n[0] ;
             vector<double>::iterator iter ;
        
             for(iter = n.begin() ; iter != n.end() ; iter++)
                  if(*iter > max)
                       max = *iter ;
        
             return max ;
        }
        

        如果您有任何问题,请告诉我。

        【讨论】:

          猜你喜欢
          • 2014-02-14
          • 1970-01-01
          • 2013-12-04
          • 1970-01-01
          • 2020-07-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多