我试图在数组中创建随机数,然后找到该数组中的最小数字。如何修改我的代码以使其工作?
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;
}