Question
Goal: Learn how to use vector and struct (In C++) Description: The program two arrays to store hours and hourly rates for employees. But the
Goal: Learn how to use vector and struct (In C++)
Description: The program two arrays to store hours and hourly rates for employees. But the simple-minded program exhibits at least two problems:
1. The sizes of the arrays are 3. What if we have more than 3 employees? Can we use a data structure to store unlimited number of employee objects?
2. We use 2 arrays to store hours and pay rates. But we need to store last name, first name, address, phone number and many others. The number of the information of an employee can easily be increased up to 20. Is it a good design to use 20 or more arrays to store the data? Obviously it is not.
Requirement: Convert the program to a better version.
Use a struct to store employee information so that we can have many fields for storing any number of employee information.
Use vector to store employee objects so that the data structure can any number of employees.
*/
#include
using namespace std;
int main() { const int SIZE = 3; double hours[SIZE]; double payRates[SIZE]; int numEmployees; int index;
// Get the number of employees. cout << "How many employees do you have? "; cin >> numEmployees;
cout << "Enter the hours worked by " << numEmployees; cout << " employees and their hourly rates. "; for (index = 0; index < numEmployees; index++) { int tempHours; // To hold the number of hours entered double tempRate; // To hold the payrate entered
cout << "Hours worked by employee #" << (index + 1); cout << ": "; cin >> tempHours; hours[index] = tempHours;
cout << "Hourly pay rate for employee #"; cout << (index + 1) << ": "; cin >> tempRate; payRates[index] = tempRate; // Add an element to payRate }
// Display each employee's gross pay. cout << "Here is the gross pay for each employee: "; cout << fixed << showpoint << setprecision(2); for (index = 0; index < numEmployees; index++) { double grossPay = hours[index] * payRates[index]; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; } return 0; }
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