Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Login

Register Now

Welcome to All Test Answers

C++ templates for the two functions minimum and maximum

Minimum/Maximum Templates
Write C++ templates for the two functions minimum and maximum. The minimum function
should accept two arguments and return the value of the argument that is the lesser of
the two. The maximum function should accept two arguments and return the value of
the argument that is the greater of the two. Design a simple driver program that demonstrates
the templates with various data types.

Answer;


// Min/Max Templates
#include<iostream>
#include <string>
using namespace std;

// Template for the min function

template <class T>
T min(T number1, T number2)
{
   return (number1 < number2)? number1 : number2;
}

// Template for the max function

template <class T>
T max(T number1, T number2)
{
   return (number1 > number2)? number1 : number2;
}

// The main function

int main()
{
   // Test min and max with int arguments.
   int num1 = 5;
   int num2 = 3;
   cout << "minimum of 5, 3 is:  " ;
   cout << min(num1, num2) << endl;
   cout << "maximum of 5, 3 is:  " ;
   cout << max(num1, num2) << endl;

   // Test min and max with double arguments.
   double num3 = 5.5;
   double num4 = 3.5;
   cout << "minimum of 5.5, 3.5 is:  " ;
   cout << min(num3, num4) << endl;
   cout << "maximum of 5.5, 3.5 is:  " ;
   cout << max(num3, num4) << endl;

   // Test min and max with string arguments.
   string hello = "hello";
   string hi = "hi";
   cout << "minimum of \"hello\" and \"hi\" is: ";
   cout << min(hello, hi) << endl;
   cout << "maximum of \"hello\" and \"hi\" is: ";
   cout << max(hello, hi) << endl;

   return 0;
}


About

Leave a reply

Captcha Click on image to update the captcha .

error: Content is protected !!