我正在研究一個函數,該函數可以找到數組中最小的元素。我試圖使用傳遞參考來修改變量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 [http://en.cppreference.com/w/cpp/algorithm/min]嗎? – ZivS
你爲什麼要回到身體的循環?它會在查看第二個元素後結束函數... – vu1p3n0x
如果您在for循環中返回,您可能會在找到最小元素之前返回! 爲什麼你有一個長度參數,當你不使用,但重新計算你的函數內的長度? – PeterO