c++ - 查找数组中的最小数字

标签 c++ arrays random min

我试图在一个数组中创建随机数,然后找到该数组中的最小数字。如何修改我的代码以使其工作?

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/

相关文章:

c++ - 为什么在定义 Q_DECLARE_PRIVATE 宏时在实现 d_fun() 中使用reinterpret_cast

c++ - ofstream 麻烦,我该如何解决?

c - C 中的 Tic tac Toe 游戏在为对手找到随机数时陷入循环

c++ - double 组中的错误值

c - rand 应该用于 IV 吗?

Mac OSX 上的 Python 2.7。无法导入随机包 环境已损坏

c++ - 如何在 linux 上为 c++ 创建动态库?

c++ - Visual Studio 中 Qt 生成的模板出错

java - 在无参数构造函数中绕过最大数组大小

java - 几个 jbutton 的随机颜色