trafalgarLaww
trafalgarLaww

Reputation: 525

Determine the largest number among three numbers using C++

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.

Upvotes: 4

Views: 1111

Answers (5)

AndyG
AndyG

Reputation: 41220

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

Upvotes: 0

oisyn
oisyn

Reputation: 1386

Starting from C++11, you can do

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

Upvotes: 20

Siraj Alam
Siraj Alam

Reputation: 10085

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.

Upvotes: 0

Neha
Neha

Reputation: 3670

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

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234885

w = std::max(std::max(x, y), z);

is one way.

Upvotes: 8

Related Questions