矢量C++的指数/最大值/最小值<double>

Index/Max/Min of a Vector<double> C++

本文关键字:lt double gt 最大值 C++ 指数 矢量 最小值      更新时间:2023-10-16

我希望能够找出向量中的最高和最低元素,并找出当前高/低数字的位置/索引。例如,

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

假设用户输入的4.3 1.0 2.99 43.5

我希望结果说

The highest number is 43.5 at position 4
The lowest number is 1.0 at position 2

我想知道是否有任何方法可以在不使用MIN_ELEMENT/MAX_ELEMENT函数的情况下实现此代码,并使用for loop?

进行操作?

我想使用以下内容:

for (int i=0;i < x.size();i++)
    if ( //the number is less than ) {
        std::cout << "The lowest number is...... at position .....";
    if ( //the number is greather than ) {
        std::cout << "The highest number is......at position......";

将每个数字与到目前为止找到的最大最大/分钟进行比较。
如果它更大/较小,则用它更换最大/分钟,并记下索引

您需要一个最大和最小变量和两个索引 - 如果最大和最小为

,请小心设置初始值的设置。

为此,您需要存储最高和最低元素的索引,并将它们与每个迭代的当前元素进行比较。

// Note: the below code assumes that the container (vector) is not empty
//    you SHOULD check if the vector contains some elements before executing the code below
int hi, lo;    // These are indices pointing to the highest and lowest elements
hi = lo = 0;   // Set hi and lo to the first element's index
// Then compare the elements indexed by hi and lo with the rest of the elements
for (int i = 1;i < x.size();i++) {
    if(x[i] < x[lo]) {
        // The element indexed by i is less than the element indexed by lo
        //    so set the index of the current lowest element to i
        lo = i;
    }
    // Below, else if is used and not if because the conditions cannot be both true
    else if(x[i] > x[hi]) {
        // Same logic as the above, only for the highest element
        hi = i;
    }
}
// Note: the position indicated by the output below will be 0-based
std::cout << "The lowest number is " << x[lo] << " at position " << lo << ".n";
std::cout << "The highest number is " << x[hi] << " at position " << hi << ".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