Jump to content
  • Advertisement
Sign in to follow this  
luasitdown

Given a list number how to get min or max?

This topic is 4570 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

Advertisement
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
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).

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 )
min = array;
if( max < array )
max = array;
}

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

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

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, maxNumber);
};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!