Sign in to follow this  

Given a list number how to get min or max?

This topic is 4358 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Assuming you mean "Given a list of numbers, how do you find the minimum or maximum value", you can use the std::min_element and std::max_element functions, which are defined in <algorithm>.

Share this post


Link to post
Share on other sites
Quote:
Original post by Alpha_ProgDes
huh?

a list number?

well if you have an array of numbers you can loop through the array and compare each number til you get to the end (assuming it's a small array < 1000).


could you give psesudo code or c++ code for it? thanks

Share this post


Link to post
Share on other sites

The prefferred C++ way:

Array:
int array[SIZE];
int min = std::min_element( array, array+SIZE );
int max = std::max_element( array, array+SIZE );

Vector:
std::vector<int> vec;
int min = std::min_element( vec.begin(), vec.end() );
int max = std::max_element( vec.begin(), vec.end() );


The manual way:

Array:
int array[SIZE];
int min = array[0];
int max = array[0];

for( int i=0; i<SIZE; i++ )
{
if( min > array[i] )
min = array[i];
if( max < array[i] )
max = array[i];
}

Vector:
std::vector<int> vec;
int min = vec[0];
int max = vec[0];

for( int i=0; i<vec.size(); i++ )
{
if( min > array[i] )
min = array[i];
if( max < array[i] )
max = array[i];
}

Share this post


Link to post
Share on other sites
if you are calculating the biggest/smallest number from an array then you can use sorting algorithms

in my opinion it is best to use sort() function that is in <algorithms.h>
it choses for you the best algorithm to use at a time and is very simple to inplement

or if you don't want to sort the whole array you can use something like this:

maxNumber = array[0];

for(i=1; i<n; ++i)
{
maxNumber = max(array[i], maxNumber);
};

Share this post


Link to post
Share on other sites

This topic is 4358 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this