在数组中寻找最小的数字

时间:2018-09-08 17:45:05

标签: 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; 

}

2 个答案:

答案 0 :(得分:1)

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]这样的元素。

答案 1 :(得分:1)

您已经找到了最小的数字。您只是没有考虑到min_element() iterators 作为输入并返回了 iterator 作为输出。您没有在第二个参数中传递有效的迭代器,并且需要取消引用输出迭代器以获取实际编号。

#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;
}
相关问题