查找存储最小值的元素

Find the element where the minimum value is stored

本文关键字:元素 最小值 存储 查找      更新时间:2023-10-16

我有一个非常微不足道的问题,但我在互联网上找不到任何涵盖它的内容。我需要在存储最小值的一维数组中找到索引。到目前为止,我找到的所有内容都只告诉您最小值的值。我尝试使用的代码是:

int min_element_loc (double a[]){
double first, last;
first = a[0];
last = a[255];
for(int i = 0;i<256;i++)
{
    if (first==last) return i;
    double smallest = first;
      while (++first!=last)
          smallest=first;
      return i;
}
return 0;
}

(数组中有 256 个元素:我知道它很乱,但它永远不会改变,而且程序不是最终版本)

谢谢

使用算法标头中的 std::min_element。

#include <vector>
#include <algorithm>
#include <iostream>
int main() {
    std::vector<double> vals = { 1.0, 2.0, 0.5, 4.2 };
    auto iter = std::min_element(vals.begin(), vals.end());
    auto idx = iter - vals.begin();
    std::cout << idx << "n";
    return 0;
}