Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Rewrite the C++ code below so the the following conditions are met: You may create any number of classes. You may edit the main() function.
Rewrite the C++ code below so the the following conditions are met:
You may create any number of classes.
You may edit the main() function.
Remove the variable string type completely from the entire program.
-- Note: Entire program includes all classes, all functions, and main().
Get rid of every if and if else statement completely from the entire program.
-- Note: Entire program includes all classes, all functions, and main().
accumulate(...), min_element(...), and max_element(...) are algorithms from the standard template library referenced with #include .
Hint: Use polymorphism.
Program:
#include
#include
#include
#include
using namespace std;
class ArrayFunction {
public:
ArrayFunction(const string& type) {
this->type = type;
}
float calculate(float array[], int size) {
if (type == "mean") {
float sum = accumulate(array, array + size, 0.0);
return sum / size;
}
else if (type == "min") {
return *min_element(array, array+size);
}
else if (type == "max") {
return *max_element(array, array+size);
}
else if (type == "first") {
return array[0];
}
return 0;
}
private:
string type;
};
int main() {
float array[] {1,2,3,7};
vector functions;
functions.push_back(new ArrayFunction("mean"));
functions.push_back(new ArrayFunction("min"));
functions.push_back(new ArrayFunction("max"));
functions.push_back(new ArrayFunction("first"));
for (int i = 0; i < functions.size(); i++) {
cout << functions[i]->calculate(array, 4) << endl;
delete functions[i];
}
return 0;
}
Example Output:
3.25
1
7
1
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started