Write a C++ program that uses the following two functions with comments on funct
ID: 3726622 • Letter: W
Question
Write a C++ program that uses the following two functions with comments on functions: T min (vector v) T max (vector v) that will accept a vector v that is passed to it and return the min and max value of all items in the vector v passed to it. For example, if T is a numeric type such as an int or double, when the min function is called, the minimum value in the vector will be returned. When the max function is called, the maximum value in the vector will be returned. Use the file minmax.txt to populate the vectors. The file will contain 5 integer values followed by five string values. Once the vectors are populated, call the min function and the max function for the integer vector. Then call the min function and the max function for the string vector. Display the results of the min and max function calls.
Explanation / Answer
In this program we will be using templates.
#include<iostream>
#include<fstream>//To use file concept
#include<string>//To use string concept
#include<vector>//To use vector concept
using namespace std;
template<class T>// Template declaration
T max(vector<T> v)//Template methd usage
{
T m=v.at(0);
int i;
for(i=0;i<5;i++)
{
if(m<v.at(i))
m=v.at(i);
}
return m;
}
template<class T>
T min(vector<T> v)
{
T m=v.at(0);
int i;
for(i=0;i<5;i++)
{
if(m>v.at(i))
m=v.at(i);
}
return m;
}
int main()
{
fstream myfile;
myfile.open("minmax.txt");//file opening
if(!myfile.is_open())
{
//When File not present stop the program
return 0;
}
double st;
int i;
string str;
vector<double> v1;//vector for first five integers
vector<string> v2;//vector for next five strings
for(i=0;i<5;i++)
{
myfile>>st;
v1.push_back(st);
}
getline(myfile,str);
for(i=0;i<5;i++)
{
getline(myfile,str);
v2.push_back(str);
}
cout<<"Maximum of Integer values is:"<<max<double>(v1)<<endl;
cout<<"Minimum of Integer values is:"<<min<double>(v1)<<endl;
cout<<"Maximum of String values is:"<<max<string>(v2)<<endl;
cout<<"Minimum of String values is:"<<min<string>(v2)<<endl;
myfile.close();
return 0;
}
We can change the program to have varied number of integers and strings.In that place add "no.of values" type (int) to the function prototypes and use appropriately.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.