返回数组中最小元素的索引
Return index of smallest element in array
>我正在尝试返回整数数组中最小元素的索引。我错过了什么吗?我输入整数后,它不返回索引。
更新:我在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.大小是边界:)
相关文章:
- 在对向量中查找元素的索引
- 当该数组的索引中没有元素时,指针指向什么?
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 如何在C++中递归地找到max元素的索引?
- 编译器(Visual C++)如何优化按索引访问矢量元素?
- 保持排序的数据结构,允许log N插入时间,并且可以返回我在log N中查找的元素的索引
- 使用推力根据索引更改某些元素的值
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- CPtrList - 如何获取元素的索引?
- 获取结构 c++ 中元素的索引
- C++ STL 数据结构常时按索引推送/弹出/随机访问,并具有指向元素的可靠指针
- 矢量指针索引处的读取元素
- C++函数返回两个 char 数组的相同索引元素
- 特征:类似 numpy 的元素索引
- 如何在另一个数组中找到一个未排序数组的不同元素索引?
- C 无法使用嵌套环将数组的元素索引
- Opencv Mat的元素索引产生垃圾
- 在c++中,当元组的元素索引在运行时已知时,是否有可能获得该元素的类型?
- 按内容访问QVector元素索引
- C++ 矢量元素索引