Avalon-96
Avalon-96

Reputation: 135

double sort in C++

I am working on a program to manage a Hotel in C++. I have a list of Rooms. All these rooms have a Floor number, Room number, and price. In one of my reports/display functions, I must print out the rooms in an order of Floor numbers, first, then by the Room numbers. What I mean by this is there will be multiple rooms on each floor so if you were sorting all the rooms on floor 1, it will sort the rooms in ascending order before it goes to the next floor.

Now, I understand how to sort the rooms by Floor number, and I know how to sort by Room number. What I don't understand is how do I combine it so that one does not over write the order of the other.

Thanks in advance.

Upvotes: 2

Views: 4548

Answers (3)

MasterID
MasterID

Reputation: 1510

Well, what must be defined is simply the less than operator.

Basically if Room1.floor < Room2.floor then Room1 must come first than Room2. If Room1.floor==Room2.floor and Room1.number < Room2.number, Room1 still need come before Room2. Otherwise Room2 has to come first.

Code:

sort(rooms.begin(),rooms.end(),[](const Room& first,const Room& second)
    {
        return first.floor<second.floor || 
            (first.floor == second.floor && first.number<second.number );
    }
);

Edit:

This code is compatible with C++11. To compile it you should use -std=c++0x flag (on g++ 4.5 and 4.6), or -std=c++11 if using g++ 4.7

Upvotes: 3

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133122

In order to sort a container of Rooms, you will need to call std::sort on it. It has an overload that takes a comparator, i.e. a function object determining which Room is "less". If you want to sort first by floors and then by room numbers, you have to write an appropriate function object (or simply function).

bool CompareByFloorAndRoomNo(const Room& r1, const Room& r2) 
{
    if(r1.FloorNo() != r2.FloorNo())
        return r1.FloorNo() < r2.FloorNo();
    return r1.RoomNo() < r2.RoomNo();
}

...

int main()
{
    ...
    std::sort(rooms.begin(), rooms.end(), CompareByFloorAndRoomNo);  
}

Upvotes: 4

lc.
lc.

Reputation: 116538

Every sorting algorithm must eventually compare two items to determine which should come first. At this point you should compare both values as one set.

Let's think about what should happen:

  • If the floor number is bigger, it is bigger.
  • If the floor number is smaller, it is smaller.
  • If the floor number is the same, compare the room number to decide.

Upvotes: 0

Related Questions