Given the following C++ code, improve the code by eliminating length calls out o
ID: 3668078 • Letter: G
Question
Given the following C++ code, improve the code by eliminating length calls out of the loop, put most used variables first when initializing variables, use prefix operators rather than postfix operators, loop unrolling, and any other improvements you would like to make to improve performance. Please note, the order of the output is not important, all data should be output.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
double sum=0;
vector<double> price;
vector<string> game;
vector<string> designer;
price.push_back(53.41);
game.push_back("Carcassone");
designer.push_back("Wrede");
price.push_back(46.51);
game.push_back("Agricola");
designer.push_back("Rosenberg");
price.push_back(31.02);
game.push_back("Puerto Rico");
designer.push_back("Seyfarth");
for(int i=0;i<game.size();i++)
{
cout<<game[i]<<" "<<endl;
}
cout<<endl;
for(int i=0;i<designer.size();i++)
{
cout<<designer[i]<<" "<<endl;
}
cout<<endl;
cout<<price[0]<<" "<<endl;
cout<<price[1]<<" "<<endl;
cout<<price[2]<<" "<<endl;
sum=price[0]+price[1]+price[2];
cout<<"The total price for all games is "<<sum<<endl;
cin.ignore();
return 0;
Explanation / Answer
The only performance improvements i see in this program are : 1) eliminating loops is data length is known and less, and 2) remove the sum variable and calculate it on the go while printing.
Please find the new improved program below :
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
vector<double> price;
vector<string> game;
vector<string> designer;
price.push_back(53.41);
game.push_back("Carcassone");
designer.push_back("Wrede");
price.push_back(46.51);
game.push_back("Agricola");
designer.push_back("Rosenberg");
price.push_back(31.02);
game.push_back("Puerto Rico");
designer.push_back("Seyfarth");
cout<<game[0]<<" "<<endl;
cout<<game[1]<<" "<<endl;
cout<<game[2]<<" "<<endl;
cout<<endl;
cout<<designer[0]<<" "<<endl;
cout<<designer[1]<<" "<<endl;
cout<<designer[2]<<" "<<endl;
cout<<endl;
cout<<price[0]<<" "<<endl;
cout<<price[1]<<" "<<endl;
cout<<price[2]<<" "<<endl;
cout<<"The total price for all games is "<<price[0]+price[1]+price[2]<<endl;
cin.ignore();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.