我试图在一个数组中创建随机数,然后找到该数组中的最小数字。如何修改我的代码以使其工作?
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]
.
关于c++ - 查找数组中的最小数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52237840/