存储数组索引值C++
Storing arrays index values C++
我目前有一个浮点数组声明和初始化,其值范围为 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);
相关文章:
- 如何在for循环中包含两个索引值的测试条件
- *无符号字符中的索引值
- 返回向量的单个索引值
- 如何在对向量排序后更改索引值?c++
- 为什么C++数组索引值是有符号的,而不是围绕size_t类型构建的(或者我错了)
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- 如何在C++中为数组分配不同的索引值
- C++枚举索引值
- 查找索引值在char表中
- 根据索引值提取特定字节
- 尝试输出所有索引值(如果找到)
- 有没有办法创建一个花哨的迭代器和相应的新数组,以便检查每个索引的索引值的条件?
- 为什么在将单词从文本文件C++到行进行多重映射时获得额外的索引值
- C++使用 min_element 或 max_element 时检索向量中的索引值
- 如何使用二进制索引树来计算小于索引值的元素数量
- 存储数组索引值C++
- 在 for 循环中使用 int 以外的数据类型作为索引值C++
- 向函数传递特定的数组索引值
- C++从迭代器中获取整数形式的索引值
- 将数组中的所有数字更改为其索引值