Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Sorting by different members of a class

I have a vector of 10 vehicle objects.
class vehicle
{
int ID;
string name;
float size;
float length;
}

using sort in <algorithm>, how do you sort by individual fields within this class?

what happens when I need to do comparison between two vehicle objects?
bool operator==(vehicle & itemA, vehicle & itemB);
bool operator<(vehicle & itemA, vehicle & itemB);
there are 4 possible fields that I need to compare but they can't all use the same parameter list.

I guess I can brute force it and write 4 different sort_by_xyz function and then map the corresponding field to a new array and then sort that array. But this seems to be very inefficient.
[741 byte] By [rssmps] at [2007-11-11 7:44:22]
# 1 Re: Sorting by different members of a class
First of all, you never need to define more than operator < since all other relational operators are synthesized from this function.
As for the different sorting criteria:
You can add an additional data member to vehicle. This data member tells the overloaded < which member it should compare:

bool operator< (const vehicle& a, const vehicle& b)
{
switch (b.get_sorting_flag())
case ID:
//do ID stuff
return a.ID<b.ID
case PRICE:
...
default:
//perform default comparison

}

The flag itself should be a member of vehicle. Give it a default value at contruction time and define matching getter and setter function to modify and examine it.
Danny at 2007-11-11 21:01:55 >