user2001875
user2001875

Reputation:

Comparing many numbers to find minimum and maximum

To keep it simple lets say I have 3 whole numbers (integers) I know I can find the highest by using something like:

if(num1 > num2 && num1 > num3)
    cout << num1 << endl;
if(num2 > num1 && num2 > num3)
    cout << num2 << endl;
if(num3 > num1 && num3 > num2)
    cout << num3 << endl; 

And the lowest:

if(num1 < num2 && num1 < num3)
    cout << num1 << endl;
if(num2 > num1 && num2 > num3)
    cout << num2 << endl;
if(num3 < num1 && num3 < num2)
    cout << num3 << endl;

How can I get something like this to deal with equalities like 221,111,122,121. edit: Im trying to stay away from any prebuilt math includes as that is not the point here..

Upvotes: 4

Views: 4820

Answers (1)

Mark B
Mark B

Reputation: 96241

You should look into storing your values in a container such as vector (I can't tell if you will always have three or if you may vary in number). Then you can use std::min_element and std::max_element which are already written and tuned to find the min/max from a sequence of values.

Upvotes: 4

Related Questions