[英]Finding the smallest number in an array
我正在嘗試在數組中創建隨機數,然后在該數組中找到最小的數。 如何修改我的代碼以使其正常工作?
using namespace std;
int one, two, three, four;
int main(){
srand (time(NULL));
one = rand() % 6 + 1;
two = rand() % 6 + 1;
three = rand() % 6 + 1;
four = rand() % 6 + 1;
int myelement [4] = {four, three, two, one};
cout << myelement, myelement[+4] << endl;
cout << min_element(myelement, myelement[+4]);
return 0;
}
std :: min_element()函數不會將解引用的指針作為參數,而這正是您使用myelement[+4]
所做的。 傳遞迭代器並返回迭代器:
auto it = std::min_element(std::begin(myelement), std::end(myelement));
std::cout << *it;
確保包含<algorithm>
標頭。
另外,這:
cout << myelement, myelement[+4] << endl;
錯誤的原因有很多。
這個:
cout << myelement;
不打印出第一個元素。 當您的數組在函數中使用時,它將轉換為指針,從而輸出指針值。
這個:
cout << myelement[+4];
不會打印第四個元素值,但是會導致未定義的行為,因為不存在myelement[+4]
這樣的元素,只有myelement[3]
。
您已經找到了最小的數字。 您只是沒有考慮min_element()
將迭代器作為輸入並返回迭代器作為輸出。 您沒有在第二個參數中傳遞有效的迭代器,並且需要取消引用輸出迭代器以獲取實際編號。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
int main(){
srand (time(NULL));
int one = rand() % 6 + 1;
int two = rand() % 6 + 1;
int three = rand() % 6 + 1;
int four = rand() % 6 + 1;
int myelement [4] = {four, three, two, one};
cout << *min_element(myelement, myelement+4);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.