in c++ Write a program that solves the problem below except that the array of po
ID: 3779722 • Letter: I
Question
in c++ Write a program that solves the problem below except that the array of pointer points to the data array in descending order of age. Consider a company that needs to sort an array Person data[10] of structures of type Person by name. struct Person { string name; int age; } In real life the Person structures may have many members and occupy a large area of memory, making it computationally expensive to move Person objects around while sorting. You can define an auxiliary array Person *pData[10], setting each entry of pData[k] to point to the corresponding entry of data[k]. Write a program that sorts the array of pointers so that when you go through pData in increasing order of index k, the entries pData[k] point to Person objects in ascending alphabetic order of names.
Explanation / Answer
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
struct Person
{
string name;
int age;
};
int main()
{
struct Person data[10];
struct Person *pData[10],*temp;
string names[] = {"a","b","c","g","z","l","p","q","r","w"};
int num[] = {4,6,34,8,13,90,33,22,18,23};
for(int i=0;i<9;i++)
{
data[i].name = names[i];
data[i].age = num[i];
pData[i] = &data[i];
}
for(int i=0;i<9;i++)
{
for(int j=i+1;j<9;j++)
{
if(pData[i]->age<pData[j]->age)
{
temp = pData[i];
pData[i] = pData[j];
pData[j] = temp;
}
}
}
for(int i=0;i<9;i++)
{
cout<<pData[i]->name<<" "<<pData[i]->age<<endl;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.