Best method for sorting a struct

I'm new to structs and arrays. I do know how to sort a single array, but how do you sort a struct. For example:


1
2
3
4
5
6
  struct apartmentInfo 						// apartment information
{                      
        string phoneNum;                    // phone number  
        float rent;                         // rental price
        bool rentalStatus;                  // apartment rented = 1; vacant apartment = 0
};

The phone number is similar to an identifier for the rental price and the status of the apartment. I haven't gotten around to writing any code for this part because I'm not sure how to go about it. Please point me in the right direction, Thank you.
Look at http://www.cplusplus.com/reference/algorithm/sort/

The algorithm uses either '<' or 'comp' to find out whether two elements are already in correct order.
Your "sort a single array" must use some comparison operation too. A version with a function, rather than operator<:
1
2
3
4
5
6
7
8
9
10
11
bool mycomp( const int & lhs, const int & rhs ) {
  return lhs < rhs;
}

// used in
if ( mycomp( arr[i], arr[j] ) ) {
  // already in ascending order
}
else {
  // equal or descending, must swap elements
}


The only thing that is more complex with structs is the comparison function:
1
2
3
4
5
6
7
8
9
10
11
12
bool mycomp( const apartmentInfo & lhs, const apartmentInfo & rhs ) {
  // return true, if lhs is logically "smaller" / "before" the rhs
  return ????;
}

// used in
if ( mycomp( arr[i], arr[j] ) ) {
  // already in ascending order
}
else {
  // equal or descending, must swap elements
}


The real question is, which order do you want?

For example, if the vacancy is the primary attribute and you want to see the vacant apartments first, then there are three possibilities:

1. Both lhs and rhs have same vacancy status and you need to use phone number and price for determining the "are these in order?"

2 lhs and rhs have different vacancy status. Phone and price do not affect.
2a lhs is vacant, already "in order"
2b lhs is not vacant, "not in order"


Operator< can be overloaded for the struct too:
1
2
3
4
5
6
7
8
9
10
11
bool operator< ( const apartmentInfo & lhs, const apartmentInfo & rhs ) {
  return ?????
}

// used in
if ( arr[i] < arr[j] ) {
  // already in ascending order
}
else {
  // equal or descending, must swap elements
}


Last edited on
Thank you for that explanation. That really helped me to get a better idea on how to write this program.
Topic archived. No new replies allowed.