【发布时间】:2020-10-24 19:42:28
【问题描述】:
我有这段代码,我怎样才能找到读数数组中的最小值位置。 例如,如果最小值是读数 [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]),如果有一种方法可以让我知道数组中的最小元素位置,我将不胜感激。
【问题讨论】:
-
您正在尝试使用 for 循环初始化数组的每个元素,现在您想获取数组中最小元素的位置?
-
嗨,尝试使用标准容器(std::array、std::vector(如果大小不固定))。这些容器有实现的方法。 en.cppreference.com/w/cpp/algorithm/min_element
-
@Celz - 标准算法也适用于原始数组。
std::min_element(std::begin(readings), std::end(readings))将给出一个指向最小元素的指针(或第一个找到的元素,如果多个元素具有相同的最小值)。std::distance(std::begin(readings), std::min_element(std::begin(readings), std::end(readings)))会将其转换为(有符号的)整数索引。 -
对于 OP - 从
count = 0循环到count < 21意味着您的代码写到了readings的末尾,因此会导致未定义的行为。循环到count < 20。我认为for中额外的;是一个错字。 -
@Peter 很高兴知道,谢谢
标签: c++ arrays position minimum