【问题标题】:Storing arrays index values C++存储数组索引值 C++
【发布时间】:2015-01-26 11:44:32
【问题描述】:

我目前有一个浮点数组声明并初始化了一系列值,例如3.2、4.4、9.8。 while 循环将数组的最高值元素添加到变量最高值中。这可以正常工作,并输出数组中的最高元素。我正在尝试找到一种方法来存储最高元素的索引,即如果值为 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;

【问题讨论】:

标签: c++ arrays indexing


【解决方案1】:

这实际上非常简单,但是您将返回一个指向元素的迭代器,而不是一个实际的索引。

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

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

const auto highestArrayVal = *it;

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

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

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    • 2014-08-04
    相关资源
    最近更新 更多