Answers
In case of any queries, please revert back.
I have explained everything in the comments step by step.
================= CODE BELOW ========================
#include <bits/stdc++.h>
using namespace std;
//declaring the class and the constructors.
// Empty constructor added for declaring array of objects.
class Country{
public:
long long int population;
long long int area;
char *name;
Country(){}
Country(long long int pop,long long int ar,char *nm){
name=nm;
population=pop;
area=ar;
}
};
int main()
{ //declaring a name array
char *nameArr[5];
nameArr[0]="A";
nameArr[1]="B";
nameArr[2]="C";
nameArr[3]="D";
nameArr[4]="E";
//declare list of objects of class Country
Country objList[5];
//provide different values to population and area
int pop=1,area=7;
for(int i=0;i<5;i++){
//declaring objects in array.
objList[i]=Country(pop,area,nameArr[i]);
pop=pop+30;
area=50;
}
//now we change the type of comparator used to sort objects. Here we check population
cout<<"============= sorting as per population =================\n";
sort(objList, objList + 5,
[](Country const & a, Country const & b) -> bool
{ return a.population < b.population; } );
for(int i=0;i<5;i++){
cout<<objList[i].population<<" "<<objList[i].name<<endl;
}
//now we change the type of comparator used to sort objects. Here we check population/area
cout<<"============= sorting as per population density =================\n";
sort(objList, objList + 5,
[](Country const & a, Country const & b) -> bool
{ return (a.population/a.area) < (b.population/b.area); } );
for(int i=0;i<5;i++){
cout<<objList[i].population<<" "<<objList[i].name<<endl;
}
//now we change the type of comparator used to sort objects. Here we check name via strcmp operation.
cout<<"============= sorting as per population density =================\n";
sort(objList, objList + 5,
[](Country const & a, Country const & b) -> bool
{ int x=strcmp(a.name,b.name);
if(x>0) return true;
return false; } );
for(int i=0;i<5;i++){
cout<<objList[i].population<<" "<<objList[i].name<<endl;
}
return 0;
}
=================== SCREENSHOTS BELOW =====================