我正在编写一个函数,用于查找数组中最小的元素。我尝试使用引用传递来修改变量s
。我是C++的新手,不确定我是否正确地使用了引用传递。有人可以确认这是否是正确的方法,或者建议更好的方法来处理使用引用传递的最小值函数吗?
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
using namespace std;
int smallestElm(int numArray[], int length, int &smallest);
int main() {
int n[3] = {2,5,3};
int s = 0;
int length = 0;
cout << smallestElm(n, length, s) << endl;
}
int smallestElm(int numArray[], int length, int &smallest) {
smallest = numArray[0];
length = sizeof (numArray) / sizeof (int);
for (int i = 1; i < length; i++) {
if (numArray[i] < smallest) {
smallest = numArray[i];
}
cout << smallest << endl;
return 0;
}
}
std::min_element
,我想到了,不知道为什么错过了你的方法... - gsamarassizeof
才能正常工作。 - stark