首页 > 解决方案 > 了解数组c ++中最小值位置的最简单方法

问题描述

我有这段代码我怎样才能找到读数数组中的最小值位置。例如,如果最小值是读数 [10],有没有办法我可以编写代码

int count = 0;
long readings[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (count = 0;count <21;count++;){
readings [count] =  time2[count] + (time3[count] * 60) + ( time4[count] * 3600);
}

我实际上是在像这样使用 if 语句。 if ( (readings[0] <= readings[1]) && (readings[2]) ) {} 但现在我想计算并比较数组中的 20 个数字(读数 [0])与(读数 [20]),如果有一种方法可以让我知道数组中的最小元素位置,我将不胜感激。

标签: c++arrayspositionminimum

解决方案


std::min_element将为您完成工作:

auto index = std::distance(std::begin(readings), std::min_element(std::begin(readings), std::end(readings)));

推荐阅读