简体   繁体   中英

Finding the smallest number in an array

I am trying to create random numbers in an array and then find the smallest number in that array. How do I modify my code to make it work?

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; 

}

The std::min_element() function does not take a dereferenced pointer as an argument which is what you are doing with myelement[+4] . Pass in the iterators and return an iterator instead:

auto it = std::min_element(std::begin(myelement), std::end(myelement));
std::cout << *it;

Make sure you include the <algorithm> header.

Also, this:

 cout << myelement, myelement[+4] << endl;

is wrong for a number of reasons.

This:

cout << myelement;

does not print out a first element. It prints the pointer value as your array gets converted to a pointer when used in a function.

This:

 cout << myelement[+4];

does not print the fourth element value but causes undefined behaviour as there is no such element as myelement[+4] , only myelement[3] .

You are already finding the smallest number. You are just not taking into account that min_element() takes iterators as input and returns an iterator as output. You are not passing a valid iterator in the 2nd parameter, and you need to dereference the output iterator to get the actual number.

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM