Write a C++ program that uses the following two functions with comments on funct
ID: 3726621 • 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
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
template <typename T>
T min (vector <T> v) {
T result = v[0];
for(int i = 0; i < v.size(); ++i) {
if(v[i] < result) {
result = v[i];
}
}
return result;
}
template <typename T>
T max (vector <T> v) {
T result = v[0];
for(int i = 0; i < v.size(); ++i) {
if(v[i] > result) {
result = v[i];
}
}
return result;
}
int main() {
ifstream in("minmax.txt");
if(in.is_open()) {
vector<int> v1;
vector<string> v2;
int num;
string str;
for(int i = 0; i < 5; ++i) {
in >> num;
v1.push_back(num);
}
for(int i = 0; i < 5; ++i) {
in >> str;
v2.push_back(str);
}
cout << "Minimum in integer vector: " << min(v1) << endl;
cout << "Maximum in integer vector: " << max(v1) << endl;
cout << "Minimum in string vector: " << min(v2) << endl;
cout << "Maximum in string vector: " << max(v2) << endl;
in.close();
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.