存储数组索引值C++

Storing arrays index values C++

本文关键字:C++ 索引值 数组 存储      更新时间:2023-10-16

我目前有一个浮点数组声明和初始化,其值范围为 3.2、4.4、9.8。while 循环将数组的最高值元素添加到可变的 highestVal 中。这按预期工作,并输出数组中的最高元素。我正在尝试找到一种方法来存储最高元素的索引,即如果值为 3.4,我还想将该值的索引存储在数组中。谁能指出我存储此索引值的基本方法是什么。

int const MAXVALUES = 10;
int counter = 0;
float floatPointNumber[MAXVALUES] = { 1.3, 9.2, 2.2, 4.4, 2.5, 2.7, 9.2, 7.9, 9.2, 9.6 };
int index = -1;
float highestArrayVal = 0;
while (counter < MAXVALUES)
{
    cout << floatPointNumber[counter] << endl;
    while (floatPointNumber[counter]>highestArrayVal)
    {
        highestArrayVal = floatPointNumber[counter];
        //index = floatPointNumber[counter];
        break;
    }
    counter = counter + 1;
}
cout << "Highest Array Value " << highestArrayVal << endl;
cout << "Index of this element " << index << endl;
return 0;

这实际上非常简单,但你会得到一个指向元素而不是实际索引的迭代器。

const auto it = max_element(begin(floatingPointNumber), end(floatingPointNumber));

这个迭代器本质上是一个指针。例如,您可以像这样找到最大元素的值:

const auto highestArrayVal = *it;

由于it是一个指针,您可能不再需要确切的索引,但如果仍然需要,则可以执行以下操作:

const auto index = distance(begin(floatingPointNumber), it);