How to sort a class by their various attributes in C++
Custom sorting classes
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
class Student
{
public:
string name;
double tuition;
};
//This functions sort by name
bool SortStudentByName ( const Student& left, const Student& right )
{
//Here you can define whatever the sort criterion
//needs to be. It can be as complicated as you wish
if ( left.name > right.name )
{
return false;
}
else if ( left.name < right.name )
{
return true;
}
//else //i.e if both are equal
}
//This function sorts by tuitions fees
bool SortStudentByTute ( const Student& left, const Student& right )
{
if ( left.tuition > right.tuition )
{
return false;
}
else if ( left.tuition < right.tuition )
{
return true;
}
}
int main()
{
Student myStudent [3]; //create an array of objects
myStudent[0].name = "sarah";
myStudent[0].tuition = 10.2;
myStudent[1].name = "carry";
myStudent[1].tuition = 11.2;
myStudent[2].name = "zog";
myStudent[2].tuition = 3;
// call the sort like this (assuming array has size of 3):
cout << "sorting by tutition fees\n";
std::sort ( myStudent, myStudent + 3, SortStudentByTute );
cout << myStudent[0].name << " " << myStudent[0].tuition << endl;
cout << myStudent[1].name << " " << myStudent[1].tuition << endl;
cout << myStudent[2].name << " " << myStudent[2].tuition << endl;
//--------------------------------------------------------
cout << "\nsorting by names\n";
std::sort ( myStudent, myStudent + 3, SortStudentByName );
cout << myStudent[0].name << " " << myStudent[0].tuition << endl;
cout << myStudent[1].name << " " << myStudent[1].tuition << endl;
cout << myStudent[2].name << " " << myStudent[2].tuition << endl;
// Or use a vector instead of the array and sort like this:
//std::sort(myStudentVec.begin(), myStudentVec.end(), SortStudentByName);
cin.get();
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.