New to C++ and need some help

I need a little help. The problem is
Write a function named maxValue that has three integer parameters. The function should compare the three values and return the highest value.

Try to write it yourself, and once you encounter problems you can't solve on your own, post them.
closed account (Dy7SLyTq)
1
2
3
4
5
6
7
8
template <class _type>
_type maxValue(_type one, _type two, _type three)
{
     if(one > two && one > three)
          return one

     //...
}
The shortest one possible:
1
2
3
4
5
template < typename T >
T max( const T& a, const T& b, const T& c )
{
    return ( a > b ? ( a > c ? a : c ) : ( b > c ? b : c ) );
}
Using the library can be even shorter:

1
2
3
4
5
template < typename T >
T max( const T& a, const T& b, const T& c )
{
    return std::max({a,b,c});
}


demo: http://ideone.com/CfS5Bp
But Fransje's is much more fun to read :)
closed account (Dy7SLyTq)
fransje's is brilliant! its even better when you try to understand it and finally get it
if you want to pass an integer array

1
2
3
4
5
6
7
8
9
10
11
12
int Max(int a[], int length)
{
   int out = a[0];

   for (int i = 1; i < length; i++)
   {
      if (a[i] > out)
         out = a[i];
   }

   return out;
}
closed account (Dy7SLyTq)
aha but fransjes takes all data types and is only one line
Yeah but you could pass a list and use an iterator. It also assumes the type has an overloaded > operator plus the OP asked for ints and said he was new to c++ :)
Thanks all. Sorry I didn't post the code originally, but I started out with

(a>b && a>c)
return a

etc etc.
Topic archived. No new replies allowed.