New to C++ and need some help

Feb 13, 2013 at 4:14pm
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.

Feb 13, 2013 at 4:20pm
Try to write it yourself, and once you encounter problems you can't solve on your own, post them.
Feb 13, 2013 at 8:49pm
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

     //...
}
Feb 14, 2013 at 4:28pm
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 ) );
}
Feb 14, 2013 at 5:05pm
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
Feb 14, 2013 at 5:42pm
But Fransje's is much more fun to read :)
Feb 14, 2013 at 9:10pm
closed account (Dy7SLyTq)
fransje's is brilliant! its even better when you try to understand it and finally get it
Feb 14, 2013 at 9:34pm
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;
}
Feb 14, 2013 at 9:47pm
closed account (Dy7SLyTq)
aha but fransjes takes all data types and is only one line
Feb 15, 2013 at 12:43am
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++ :)
Feb 18, 2013 at 3:12pm
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.