In this case, if I have int n [x] = {...} How do I find max and min from this array.

Closed due to the fact that off-topic participants Anton Shchyrov , Igor , Vladimir Martyanov , Harry , iluxa1810 17 Nov '16 at 18:27 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Anton Shchyrov, Igor, Vladimir Martyanov, iluxa1810
If the question can be reformulated according to the rules set out in the certificate , edit it .

1 answer 1

There is a standard algorithm std::minmax_element , declared in the header <algorithm> , which finds the first minimal element and the last maximal element in the sequence.

Otherwise, although this is less efficient, you can find the minimum and maximum elements of the array separately, using the algorithms std::min_element and std::max_element from the same header.

It is also not a big deal to write the corresponding functions yourself. :)

Here is a demonstration program that uses the above standard algorithms.

 #include <iostream> #include <algorithm> #include <iterator> #include <cstdlib> #include <ctime> #include <utility> int main() { const size_t N = 10; int a[N]; std::srand( ( unsigned int )std::time( nullptr ) ); std::generate( std::begin( a ), std::end( a ), [=] { return std::rand() % N;} ); for ( int x : a ) std::cout << x << ' '; std::cout << std::endl; auto minmax = std::minmax_element( std::begin( a ), std::end( a ) ); std::cout << "Minimum is " << *minmax.first << ", maximum is " << *minmax.second << std::endl; auto min = std::min_element( a, a + N ); auto max = std::max_element( a, a + N ); std::cout << "Minimum is " << *min << ", maximum is " << *max << std::endl; return 0; } 

The output to the console may look like this.

 9 8 2 3 4 6 1 3 9 0 Minimum is 0, maximum is 9 Minimum is 0, maximum is 9 
  • Thank you, is there a shorter code? - Nick
  • @Nick To make the code shorter, you can explicitly set the values ​​of the elements of the array when defining it. - Vlad from Moscow
  • @Vlad from Moscow, there is also std :: valarray, which allows two operations to determine min and max - AR Hovsepyan