如何在不使用min_element C ++ </double>的情况下在vector <double>中找到min和max

时间:2014-01-24 01:44:55

标签: c++ vector double max min

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

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

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

5 个答案:

答案 0 :(得分:1)

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

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
}

答案 1 :(得分: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 :(得分:0)

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

std::set<double> numbers;

double minValue = *numbers.begin();
double maxValue = *numbers.rbegin();

答案 3 :(得分:0)

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

如果您有任何问题,请与我们联系。

答案 4 :(得分:0)

如果您正在使用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