如何在不使用min_element C++的情况下找到向量中的最小值和最大值<double>

How to find the min and max in a vector<double> without using min_element C++

本文关键字:gt 向量 最小值 lt 最大值 double 情况下 min C++ element      更新时间:2023-10-16

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

我是C 编程的新手,我正在尝试通过迭代每个元素并确定向量中的最小值和最大双重的方法来弄清楚如何使用循环的方法。我很困惑,因为由于我们不知道向量的长度是多少,所以我不确定如何解决这个问题。我想从矢量中找到最大/分钟及其索引是什么。

vector<double> numbers;
double n;
std::cout << "Enter in numbers :";
std::getline(std::cin, n);
numbers.push_back(n);
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

您可以使用std::set<double>

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

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

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
}

如果您使用的是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

使用vector<double>::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 ;
}

让我知道您是否有任何疑问。