I'm tasked with building a program that sorts a list of employees by name and by salary using the sort stl in the c++ library. Theres a code at this site: STL Sort Comparison Function - CodeProject (see section "Function Pointer as a Comparison object")
that I've been playing around with, (it sorts a person by age ive modified it to sort by name and age), but I would like to place the boolean functions inside of the Person class instead of outside it and make the age and name variables private. However, I get an error in my main file inside "std::sort", regarding my functions "sortName" and "sortAge" and with my private variables and I'm not sure how to fix it.
sort header
Code:
class Person
{
public:
// default constructor
Person();
//constructor for age and name empty
Person(int a,string n) {
age = a;
name = n;
};
bool sortAge(Person a, Person b);
bool sortName(Person a, Person b);
private:
int age;
string name;
sort.cpp
Code:
//sorts the age
bool Person::sortAge(Person a, Person b)
{
return a.age < b.age;
}
//sorts the name
bool Person::sortName(Person a, Person b){
return a.name < b.name;
}
int main()
{
vector<Person> vecPerson;
vecPerson.push_back(Person(22,"Calvin"));
vecPerson.push_back(Person(20,"James"));
vecPerson.push_back(Person(30,"Benny"));
vecPerson.push_back(Person(28,"Alison"));
vecPerson.push_back(Person(35,"Major"));
vecPerson.push_back(Person(39,"Mark"));
//sorted by name
cout << "******Sorted by Names*****\n";
std::sort(vecPerson.begin(), vecPerson.end(),sortName);
for(size_t i=0; i<vecPerson.size(); ++i)
std::cout<<vecPerson[i].name<<", "<<vecPerson[i].age<<std::endl;
//sorts by number
cout << "*****Names Sorted by Age*****\n";
std::sort(vecPerson.begin(),vecPerson.end(),sortAge);
for(size_t i=0; i<vecPerson.size(); ++i)
std::cout<<vecPerson[i].age<<", "<<vecPerson[i].name<<std::endl;
return 0;
}