返回数组中最小元素的索引

Return index of smallest element in array

本文关键字:元素 索引 数组 返回      更新时间:2023-10-16

>我正在尝试返回整数数组中最小元素的索引。我错过了什么吗?我输入整数后,它不返回索引。

更新:我在int main()结束时收到有关阵列堆栈损坏的错误。谢谢。我的代码如下:

#include <iostream>
#include <conio.h>
using namespace std;
int indexofSmallestElement(double array[], int size);
int main()
{    
int size = 10; 
double array[10];
for (int i = 0; i <= size; i++)
{
    cout << "Enter an integer: " << endl;
    cin >> array[i];
}
indexofSmallestElement(array, size);
}
int indexofSmallestElement(double array[], int size)
{
int index = 0;
if (size != 1)
{
    int n = array[0];
    for (int i = 1; i < size; i++)
    {
        if (array[i] < n)
        {
            n = array[i];
            index = i;
        }
    }
}
return index;
}

许多人向您展示了他们的indexofSmallestElement变体。我将包括我的以及为什么我认为它更好的解释:

int indexofSmallestElement(double array[], int size)
{
    int index = 0;
    for(int i = 1; i < size; i++)
    {
        if(array[i] < array[index])
            index = i;              
    }
    return index;
}

您会注意到我取消了n变量,您用来保存迄今为止遇到的最小值。我这样做是因为,根据我的经验,必须保持两个不同的事情同步可能是微妙错误的根源。即使在这种简单的情况下,它也是多个错误的根源,其中最重要的是您的n被声明为int,但您在其中分配了 double 类型的值。

底线:取消n变量,只跟踪一件事:索引。


更新:当然,不用说,对于 C++17,这个问题唯一真正可以接受的答案是使用 std::min_element

#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstdint>
#include <array>
#include <vector>
template <typename Iter>
auto indexofSmallestElement(Iter first, Iter last)
{
    return std::distance(first,
        std::min_element(first, last));
}
template <typename T, std::size_t N>
auto indexofSmallestElement(std::array<T, N> arr)
{
    return std::distance(std::begin(arr),
        std::min_element(std::begin(arr), std::end(arr)));
}
template <typename T>
auto indexofSmallestElement(std::vector<T> vec)
{
    return std::distance(std::begin(vec),
        std::min_element(std::begin(vec), std::end(vec)));
}

int main(int, char **)
{
    int arr[10] = { 7, 3, 4, 2, 0, 1, 9, 5, 6, 8 };
    auto x = indexofSmallestElement(std::begin(arr), std::end(arr));
    std::cout
        << "The smallest element in 'arr' is at index "
        << x << ": " << arr[x] << "n";
    std::array<float, 5> fa { 0.0, 2.1, -1.7, 3.3, -4.2 };
    auto y = indexofSmallestElement(fa);
    std::cout
        << "The smallest element in 'fa' is at index "
        << y << ": " << fa[y] << "n";
    return 0;
}

它应该是n = array[0]而不是array[0] = n。这意味着您假设数组的第一个元素在开始时是最小的,然后将其与其他元素进行比较。

此外,在您的循环中,您超出了数组的界限。for 循环应该运行到 i < size 而不是 i <= size

你的代码应该是这样的。

int indexofSmallestElement(double array[], int size)
{
  int index = 0 ;
  double n = array[0] ;
  for (int i = 1; i < size; ++i)
  {
    if (array[i] < n)
    {
        n = array[i] ;
        index = i ;
    }
  }
 return index;
}
循环中的

使用array[i]和index = i.大小是边界:)