You should use C++'s standard sort function, std::sort
, declared in the <algorithm>
header.
When you sort using a custom sorting function, you have to provide a predicate function that says whether the left-hand value is less than the right-hand value. So if you want to sort by name first, then by ID, then by amount due, all in ascending order, you could do:
bool customer_sorter(Customer const& lhs, Customer const& rhs) {
if (lhs.Name != rhs.Name)
return lhs.Name < rhs.Name;
if (lhs.Id != rhs.Id)
return lhs.Id < rhs.Id;
return lhs.AmountDue < rhs.AmountDue;
}
Now, pass that function to your sort
call:
std::sort(customers.begin(), customers.end(), &customer_sorter);
This assumes you have an STL container (and not an array, like you have in your sample code) called customers
containing customers.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…