Reputation: 71
I know this question has been asked before in similar circumstances, however I am new to C++ and cannot figure out what needs to be done or why it has to be done. Basically I am using a Person object that I created which has the variables name, age, height, and weight. I need to run a Quick Sort on the Person objects that I have created and sort them by age.
Person Class:
class Person{
private:
string name;
int age, height, weight;
public:
Person(string name = "empty", int age = 0, int height = 0, int weight = 0)
{
this->name = name;
this->age = age;
this->height = height;
this->weight = weight;
};
Quick Sort Method:
// Quick Sort
void QuickSort(Person *A, int start, int end){
if(start < end){
int p = partition(A, start, end);
QuickSort(A, start, p - 1);
QuickSort(A, p + 1, end);
}
}
int partition(Person *A, int start, int end){
Person pivot = A[end];
int p = start;
for(int i = start; i <= end - 1; i++){
if(A[i] <= pivot){
Person temp = A[i]; A[i] = A[p]; A[p] = temp;
p++;
}
}
Person temp = A[end]; A[end] = A[p]; A[p] = temp;
return p;
}
I am getting the error "Invalid operands to binary expression ('Person' and 'Person) on the line:
if(A[i] <= pivot)
Any help would be appreciated because I have tried multiple things and I have looked it up but cannot get other suggestions to work in this situation. I would appreciate an explanation as to why I was getting this error too if possible. Thanks!
Upvotes: 2
Views: 297
Reputation: 781096
You said you want to sort by age, so you need to compare their ages:
if (A[i].age <= pivot.age)
Your code gets an error because you haven't defined a <=
operator for your Person
class.
Upvotes: 3
Reputation: 113
C++ doesn't automatically know how to perform a comparison on class Person.
If you just want to sort by age, try
if(A[i].age <= pivot.age)
If you want to learn about defining special operators so that "Person <= Person" will work automatically, check out cppreference.com: http://en.cppreference.com/w/cpp/language/operators
Upvotes: 5