4

How can I determine the largest number among three numbers using C++?

I need to simplify this

 w=(z>((x>y)?x:y)?z:((x>y)?x:y));

Conditionals do not simplify this.

trafalgarLaww
  • 495
  • 6
  • 14
  • 4
    Define "simplify". If it's a code golf problem you should post it here: https://codegolf.stackexchange.com/ – XCS Nov 21 '17 at 13:37
  • Possible duplicate of [Find maximum of three number in C without using conditional statement and ternary operator](https://stackoverflow.com/questions/7074010/find-maximum-of-three-number-in-c-without-using-conditional-statement-and-ternar) – Neha Nov 21 '17 at 13:44
  • `(x > y) ? (x > z ? x : z) : (y > z ? y : z);` is better ordering of the brackets.. There is also `std::max_element(std::begin(array), std::end(array))` which would give you the position in the array of the maximum element. – Brandon Nov 21 '17 at 13:48
  • @NehaGupta Not a dupe; that question is for C – Justin Nov 22 '17 at 22:23

5 Answers5

20

Starting from C++11, you can do

w = std::max({ x, y, z });
oisyn
  • 985
  • 4
  • 12
8
w = std::max(std::max(x, y), z);

is one way.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
2

big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;

Neha
  • 2,888
  • 3
  • 12
  • 25
0

Use the simple if condition

int w = x;

if(y > w)
  w = y;
if(z > w)
  w = z;

Where w is the max among three.

Siraj Alam
  • 7,620
  • 6
  • 46
  • 63
0

A variant on oisyn's answer (use an initializer list) and Bathesheba's answer (invoke no copies) is to use std::ref to create an initializer list of references, and then use std::max normally:

using std::ref;
w = std::max({ref(x), ref(y), ref(z)});

This is only advantageous if creating a reference is cheaper than creating a copy (and it isn't for primitives like int)

Demo

Community
  • 1
  • 1
AndyG
  • 38,029
  • 8
  • 100
  • 134