Using C++ Re-do Problem 2, but this time you cannot assume an array size of 20.
ID: 3835672 • Letter: U
Question
Using C++ Re-do Problem 2, but this time you cannot assume an array size of 20. Instead ask the user for the size of the array and using dynamic memory allocation, create an array of the appropriate size. Assume that the user knows the exact of the array the program will need to process. HINT: This is the same as dynamic memory allocation that we saw in Chapter 9. Remember, what we use in dynamic memory allocation—a data type, a corresponding pointer, and an array size. Think what should be the data type and array size for your program.
Explanation / Answer
#include<iostream>
#include<fstream>
using namespace std;
struct Employee {
string lastName;
string firstName;
double salary;
int id;
};
void buubleSort(struct Employee a[], int n) {
Employee temp;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(a[j-1].salary > a[j].salary){
//swap the elements!
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp;
}
}
}
}
int main() {
int *pvalue = NULL;
pvalue = new int;
cout << "Enter the size of the array: ";
cin >> *pvalue;
const int size = *pvalue;
Employee *emp = new Employee[size];
ifstream inputFile;
inputFile.open("HW10Prob1.dat");
if (inputFile.is_open()) {
for(int i=0;i<size;i++){
inputFile>>emp[i].lastName>>emp[i].firstName>>emp[i].salary>>emp[i].id;
}
}
buubleSort(emp, size);
for(int j=0;j<size;j++){
cout<<"Last Name: "<<emp[j].lastName<<" "<<"First Name: "<<emp[j].firstName<<" "<<"Salary: "<<emp[j].salary<<" "<<"ID: "<<emp[j].id<<endl;
}
inputFile.close();
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter the size of the array: 8
Last Name: Lorena First Name: Emil Salary: 43000 ID: 225478
Last Name: Tereza First Name: Santeri Salary: 48000 ID: 136478
Last Name: John First Name: Harris Salary: 50000 ID: 113785
Last Name: Yannic First Name: Lennart Salary: 58000.6 ID: 369854
Last Name: Adam First Name: Johnson Salary: 68500 ID: 321258
Last Name: Lisa First Name: Smith Salary: 75000.5 ID: 254785
Last Name: Tristen First Name: Major Salary: 75800.8 ID: 102596
Last Name: Sheila First Name: Smith Salary: 150000 ID: 165478
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.