存储数组索引值C ++

时间:2015-01-26 11:44:32

标签: c++ arrays indexing

我目前有一个浮点数组已声明并初始化了一系列值,例如: 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;

1 个答案:

答案 0 :(得分:0)

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

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

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

const auto highestArrayVal = *it;

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

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